Okay what the heck am I doing wrong? I am doing this on Ubuntu and I want this to take the system command "ls" and a parameter such as "-a" and then have the child execute it and then the parent just print something out. I can't understand why I keep getting "Parent" returned twice. Any ideas?
#include <stdio.h> #include <sys/types.h> #include <time.h> #include <stdlib.h> #include <sys/time.h> #include <unistd.h> #include <sys/wait.h> void Cprocess(char *commands, char *scommands[]); void Pprocess(void); void main(int argc, char *argv[]) { char *sendcommand[] = {argv[1],argv[2],0}; char *commands = argv[0]; int pid; if((pid=fork()) ==-1) { perror("Error!!\n"); } else if(pid==0) Cprocess(commands, sendcommand); else { wait(0); printf("Parent\n"); } } void Cprocess(char *argv1, char *argv2[]) { execvp(argv1, argv2); exit(19); } That wasn't very nice of me here is the command I enter:
./filename ls -a Here is my result:
filename1 filename2 filename3 Parent Parent
commandwhich isargv[0], which is the current program. Presumably, you meant to copyargv[1]rather thanargv[0]? Or you could do without the separatecommandand simply usesendcommand[0]as the first argument toexecvp(). I've not tracked why you don't get many copies of the child running the parent again, though.