How can I implement chmod command on file by using exec? I would appreciate if anyone can provide me a code.
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).
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.
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.