fork() and exec() Two Child Processes

Deadly 提交于 2019-12-06 17:03:41
else if(cpid_a == 0) { // code for child process A
    execlp("/bin/ls", "ls", NULL);

If this calls succeeds, the following statement, and nothing that follows will ever be executed. That's how exec() works. The immediately-following fork() never occurs. That's simply how exec() works. If exec() succeeds, it never returns. The replacement process gets executed in its place.

You even added the 100% correct comment, above: "code for child process A". Everything inside the if() statement is "code for child process A", and gets executed when fork() returns 0.

You also correctly stated that you want the parent process to fork a second process. Well, you need to have that code obviously get executed by the parent process, and not the child process:

else if(cpid_a == 0) { // code for child process A
    execlp("/bin/ls", "ls", NULL);
    exit(1);
} else {
    cpid_b = fork();

  // The rest of the code.

Now, the parent process goes ahead and fork() a second time, proceeded on the rest of your plan.

P.S. The exit() is just for a good measure. The only time exec() returns is when exec() fails to execute the given process. Highly unlikely, in the case of /bin/ls; if it's missing you have bigger problems to worry about. Still, that's the technically correct thing to do, since continuing execution at that point will result in complete chaos. Again, if /bin/ls is missing that's going to be the least of the problems, but this can also happen if, say, the system ran out of memory and can't execute it for that reason; in which case there's no need to add fuel to the fire; but rather have the process die anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!