views:

132

answers:

3

How can I implement chmod command on file by using exec? I would appreciate if anyone can provide me a code.

+1  A: 

From C code, directly calling chmod(2) will almost certainly be a better choice than going through the whole hassle of fork()ing and exec()ing.

Admittedly, most of that hassle is the fork() part, and if your program does not need to do anything else after the exec() call, then just running one of the exec() family functions without forking is reasonably fine (for an exercise in using exec(), that is).

ndim
I know, but this is my exercise to do it with fork - exec.. And I don't understand it.
Tell us what you don't understand.
msw
The working of the exec. So If you gave me an example about chmod with exec, I'd be very happy.
A: 

try this: http://support.sas.com/documentation/onlinedoc/sasc/doc/lr2/execve.htm also see: http://linux.about.com/library/cmd/blcmdl3_execvp.htm

  #include <sys/types.h>
  #include <unistd.h>
  #include <stdio.h>

  main()
  {
     pid_t pid;
     char *parmList[] = {"/bin/chmod", "0700", "/home/op/biaoaai/bead",NULL}; 

     if ((pid = fork()) ==-1) //fork failed
        perror("fork error");
     else if (pid == 0) { //child (pid==0 if child)
        execvp("chmod", parmList);
        printf("Return not expected. Must be an execve error.n");
     } else { //parent (pid==child process)
        //parent specific code goes here
     }
  }

Edit: I never actually compiled... updated with users working paramList.

Shiftbit
It says: error: too few arguments to function execve. So I changed it to execvp, then I can compile it, but it don't work. Do you know what can be the problem?
This is working! Thx guys!
char *parmList[] = {"/bin/chmod", "0700", "/home/op/biaoaai/bead",NULL};execvp("chmod", parmList);
Its generally frowned upon to give complete / working code in answers to homework questions.
Tim Post
-1: for wearing out the OP's ctrl-c and ctrl-v keys.
Juliet
+1  A: 

I'm not going to show you a working model, but execve() works like this:

char *args[] = {"foo", "argument1", "argument2", (char *)NULL};

... handle forking ....

res = execve("/sbin/foo", args, (char *)NULL);

... handle execve() failing ....

The third argument to execve() is left as an exercise for the reader to research, NULL may or may not be suitable for your assignment. Additionally, its up to you to determine what type res should be and what it should equal on success. Notice casting NULL.

The single UNIX specification is usually a good place to start.

Tim Post