C++ fork() and execv() problems

Ahmet Keskin picture Ahmet Keskin · Oct 19, 2009 · Viewed 10.9k times · Source

I am kind of newbie on C++, and working on a simple program on Linux which is supposed to invoke another program in the same directory and get the output of the invoked program without showing output of the invoked program on console. This is the code snippet that I am working on:

    pid_t pid;
    cout<<"General sentance:"<<endl<<sentence<<endl;
    cout<<"==============================="<<endl;
    //int i=system("./Satzoo");
    if(pid=fork()<0)
        cout<<"Process could not be created..."<<endl;
    else
    {
        cout<<pid<<endl;
        execv("./Satzoo",NULL);
    }
    cout<<"General sentance:"<<endl<<sentence<<endl;
    cout<<"==============================="<<endl;

One of the problem I encounter is that I am able to print the first two lines on console but I cant print the last two lines. I think the program stops working when I invoke the Satzoo program. Another thing is that this code invokes Satzoo program twice, I dont know why? I can see the output on screen twice. On the other hand if I use system() instead of execv(), then the Satzoo works only once.

I haven't figured out how to read the output of Satzoo in my program.

Any help is appreciated.

Thanks

Answer

BobbyShaftoe picture BobbyShaftoe · Oct 19, 2009

You aren't distinguisng between the child and the parent process after the call to fork(). So both the child and the parent run execv() and thus their respective process images are replaced.

You want something more like:

pid_t pid;
printf("before fork\n");

if((pid = fork()) < 0)
{
  printf("an error occurred while forking\n");
}
else if(pid == 0)
{
  /* this is the child */
  printf("the child's pid is: %d\n", getpid());
  execv("./Satzoo",NULL);
  printf("if this line is printed then execv failed\n");
}
else
{
  /* this is the parent */
  printf("parent continues execution\n");
}