I have an example here:
我在这里有一个例子:
int runcmd(char *cmd)
{
char* argv[MAX_ARGS];
pid_t child_pid;
int child_status;
parsecmd(cmd,argv);
child_pid = fork();
if(child_pid == 0) {
/* This is done by the child process. */
execvp(argv[0], argv);
/* If execvp returns, it must have failed. */
printf("Unknown command\n");
exit(0);
}
else {
/* This is run by the parent. Wait for the child
to terminate. */
do {
pid_t tpid = wait(&child_status);
if(tpid != child_pid) process_terminated(tpid);
} while(tpid != child_pid);
return child_status;
}
}
This one is a classic example of fork() After fork(), the control goes to child process. How can I keep in parent process, do stuffs. Instead of jumping to child immediately?
这是fork()的经典示例在fork()之后,控件转到子进程。如何保持父进程,做东西。而不是立即跳孩子?
Thank you
3 个解决方案
#1
4
The child will always be the child. The parent will always be the parent. fork()
creates a new process, and each runs separately. If you want to do something in the parent then do it in the parent.
孩子永远是孩子。父母将永远是父母。 fork()创建一个新进程,每个进程单独运行。如果您想在父级中执行某些操作,请在父级中执行此操作。
#2
0
Once you call fork
, the scheduler decides whether the parent or child get to run first. They may even run in parallel: multiple CPUs and cores are common nowadays.
调用fork后,调度程序将决定父项或子项是否先运行。它们甚至可以并行运行:现在多个CPU和核心很常见。
If there is some action that the parent has to take before the child runs, then you should place that action before the fork
. Otherwise the parent and child have to synchronize somehow.
如果在子进程运行之前父进程必须执行某些操作,则应将该操作放在fork之前。否则父母和孩子必须以某种方式同步。
#3
0
When fork() is executed, two separate OS processes are created. So the OS scheduler will then decide when each gets run, you cannot decide that.
执行fork()时,会创建两个单独的OS进程。因此OS调度程序将决定每个运行时间,您无法做出决定。
#1
4
The child will always be the child. The parent will always be the parent. fork()
creates a new process, and each runs separately. If you want to do something in the parent then do it in the parent.
孩子永远是孩子。父母将永远是父母。 fork()创建一个新进程,每个进程单独运行。如果您想在父级中执行某些操作,请在父级中执行此操作。
#2
0
Once you call fork
, the scheduler decides whether the parent or child get to run first. They may even run in parallel: multiple CPUs and cores are common nowadays.
调用fork后,调度程序将决定父项或子项是否先运行。它们甚至可以并行运行:现在多个CPU和核心很常见。
If there is some action that the parent has to take before the child runs, then you should place that action before the fork
. Otherwise the parent and child have to synchronize somehow.
如果在子进程运行之前父进程必须执行某些操作,则应将该操作放在fork之前。否则父母和孩子必须以某种方式同步。
#3
0
When fork() is executed, two separate OS processes are created. So the OS scheduler will then decide when each gets run, you cannot decide that.
执行fork()时,会创建两个单独的OS进程。因此OS调度程序将决定每个运行时间,您无法做出决定。