仅在挂起 child 后运行 Parent 进程代码
Runing Parent Process code only after suspending child
我有一个进程P1。我正在通过 fork 创建一个 child,然后在 fork 的 child 部分内执行。我想挂起 child,然后仅在 child 挂起后才执行其余的 parent 代码。知道我该怎么做吗?
int pid=fork();
if(pid==0)
{
//Do something in here
}
else
{
暂停 child 并执行其他操作,仅在 child 暂停后
}
在我看来,最简单的同步机制就是一个简单的管道。如果您希望 child 在执行之前等待,请让它在读取时阻塞。例如:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char **argv)
{
int p1[2];
int c;
if( pipe(p1)) {
perror("pipe");
return EXIT_FAILURE;
}
switch( fork() ) {
case -1:
perror("fork");
return EXIT_FAILURE;
case 0:
read(p1[0], &c, 1); /* wait on the parent */
close(p1[0]);
close(p1[1]);
execlp("echo", "echo", "foo", NULL);
perror("exec");
return EXIT_FAILURE;
default:
puts("This will always print first");
fflush(stdout);
write(p1[1], &c, 1); /* tell the child to continue */
close(p1[1]);
close(p1[0]);
}
return EXIT_SUCCESS;
}
如果您希望 child 在挂起之前执行,您可以尝试发送 SIGSTOP 并使用 SIGCONT 使其继续,但实际上没有意义。如果这样做,您将无法知道 child 何时停止,甚至可能 运行 在您发送 SIGSTOP 之前完成。如果您有其他一些外部同步方法(例如,child 正在写入文件系统并且您可以监视它),您应该使用它来使 child 自行挂起。尝试使用 SIGSTOP/SIGCONT 将有许多你需要处理的竞争条件。最好的办法是用上面的东西延迟 exec
。
我有一个进程P1。我正在通过 fork 创建一个 child,然后在 fork 的 child 部分内执行。我想挂起 child,然后仅在 child 挂起后才执行其余的 parent 代码。知道我该怎么做吗?
int pid=fork();
if(pid==0)
{
//Do something in here
}
else
{ 暂停 child 并执行其他操作,仅在 child 暂停后 }
在我看来,最简单的同步机制就是一个简单的管道。如果您希望 child 在执行之前等待,请让它在读取时阻塞。例如:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int
main(int argc, char **argv)
{
int p1[2];
int c;
if( pipe(p1)) {
perror("pipe");
return EXIT_FAILURE;
}
switch( fork() ) {
case -1:
perror("fork");
return EXIT_FAILURE;
case 0:
read(p1[0], &c, 1); /* wait on the parent */
close(p1[0]);
close(p1[1]);
execlp("echo", "echo", "foo", NULL);
perror("exec");
return EXIT_FAILURE;
default:
puts("This will always print first");
fflush(stdout);
write(p1[1], &c, 1); /* tell the child to continue */
close(p1[1]);
close(p1[0]);
}
return EXIT_SUCCESS;
}
如果您希望 child 在挂起之前执行,您可以尝试发送 SIGSTOP 并使用 SIGCONT 使其继续,但实际上没有意义。如果这样做,您将无法知道 child 何时停止,甚至可能 运行 在您发送 SIGSTOP 之前完成。如果您有其他一些外部同步方法(例如,child 正在写入文件系统并且您可以监视它),您应该使用它来使 child 自行挂起。尝试使用 SIGSTOP/SIGCONT 将有许多你需要处理的竞争条件。最好的办法是用上面的东西延迟 exec
。