【发布时间】:2016-08-01 20:21:37
【问题描述】:
我想分叉多个进程并为每个子进程分配它自己的终端窗口,以便可以轻松地演示 IPC。 分叉进行得很好,如果我在同一个终端上运行子进程,它运行得很好。 但是为了让每个子进程都有自己的终端窗口,我这样做了
execl("/usr/bin/xterm", "xterm", "-e", "yourprogram", NULL);
程序在新窗口中运行,但它的 PID 与派生该进程的父进程显示的不同。我做错了什么?
谢谢
edit1 - 这是我的主要功能(父进程)。我分叉了 4 个子进程。我希望每个子进程都有自己的终端窗口。然而,子进程刚刚退出,具有不同 PID 的新进程继续在新终端中运行。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
pid_t pid[4];
int i = 0;
int status;
//Fork four new processes
for(i=0; i<4; i++)
{
pid[i] = fork();
if(pid[i] == 0 && i == 0)
{
execl("/usr/bin/xterm", "xterm", "./child1", NULL);
exit(1);
}
else if(pid[i] == 0 && i == 1)
{
execl("/usr/bin/xterm", "xterm", "./child2", NULL);
exit(1);
}
else if(pid[i] == 0 && i == 2)
{
execl("/usr/bin/xterm", "xterm", "./child3", NULL);
exit(1);
}
else if(pid[i] == 0 && i == 3)
{
execl("/usr/bin/xterm", "xterm", "./child4", NULL);
exit(1);
}
else
{
//Parent process
printf("The main function has forked a process with pid: %d\n", pid[i]);
}
}
for(i=0;i<4;i++)
{
status = waitpid(pid[i], NULL, 0);
if(status == pid[i])
printf("%d: Process Terminated Successfully\n", pid[i]);
else
{
perror("waitpid");
exit(1);
}
}
return 1;
}
edit2 - 添加 ps -u 输出:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
dell-pc 3024 0.1 0.0 26872 5480 pts/0 Ss 16:54 0:00 bash
dell-pc 3038 0.0 0.0 4200 632 pts/0 S+ 16:54 0:00 ./main
dell-pc 3039 22.5 0.1 109240 11116 pts/0 S+ 16:54 0:01 xterm ./child1
dell-pc 3040 26.1 0.1 109240 11268 pts/0 R+ 16:54 0:02 xterm ./child2
dell-pc 3041 28.7 0.1 109240 11180 pts/0 S+ 16:54 0:02 xterm ./child3
dell-pc 3042 27.0 0.1 109240 11288 pts/0 S+ 16:54 0:02 xterm ./child4
dell-pc 3044 4.1 0.0 4200 648 pts/24 Ss+ 16:55 0:00 child3
dell-pc 3046 3.7 0.0 4200 680 pts/26 Ss+ 16:55 0:00 child4
dell-pc 3048 3.8 0.0 4200 792 pts/25 Ss+ 16:55 0:00 child2
dell-pc 3050 3.3 0.0 4200 660 pts/14 Ss+ 16:55 0:00 child1
dell-pc 3060 2.0 0.0 26816 5412 pts/27 Ss 16:55 0:00 bash
dell-pc 3072 0.0 0.0 22648 2688 pts/27 R+ 16:55 0:00 ps -u
edit3:添加 main: 的输出:
The main function has forked a process with pid: 3491
The main function has forked a process with pid: 3492
The main function has forked a process with pid: 3493
The main function has forked a process with pid: 3494
3491: Process Terminated Successfully
3492: Process Terminated Successfully
3493: Process Terminated Successfully
3494: Process Terminated Successfully
【问题讨论】:
-
您可能在这里有答案:stackoverflow.com/questions/11040334/…
-
看到了该解决方案,但它不使用 C 代码。我需要使用 C
-
我想你没有做错任何事。终端使用另一个子进程运行您需要的命令。
-
但是父进程和子进程返回的子进程的PID(使用getpid())是不同的。这就是我认为有问题的原因。此外,子进程(具有父进程给出的 PID)实际上在 exec 调用之后退出。可能,execl 在内部分叉?
-
因为你有三个进程,你的主程序,它是运行 xterm 的子进程,它有他自己的子进程运行你的命令。