我必须创建prog1,它需要一个参数,有几个孩子必须创建。(例子"。/prog1 5" -将创建5个子)每个子将生成从1到20的随机数。这个数字将给execl,它将启动prog2(在同一个文件夹中),它将这个随机数作为参数。Prog2应该休眠这个随机数的时间。之后,它应该返回这个随机数到父节点。
我创造了这样的东西,但它仍然不能正常工作。
prog1:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int n, i, pid;
int u = getppid();
int procesy = 0;
pid_t proc_id;
n = atoi(argv[1]);
for(i = 0; i < n; i++)
{
proc_id = fork();
if(proc_id==0)
{
srand(getpid());
u = 1 + rand()%20;
execl("./prog2", "prog2", u,0);
}
else
{
procesy++;
}
}
if(u == getppid())
{
for(i = 0; i < n; i++)
{
pid = wait(&u);
printf("Process %d enden", pid);
procesy--;
}
if(procesy == 0) printf("endcn");
}
return 1;
}
prog2:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
int n;
n = atoi(argv[1]);
sleep(n);
exit(n);
}
将循环修改为如下所示,以便正确调用execl():
if(proc_id==0)
{
char arg[16];
srand(getpid());
sprintf(arg, "%d", 1 + rand()%20);
execl("./prog2", "prog2", arg, 0);
printf("I should not be here!n");
exit(-1);
}
则去掉if(u == getppid())
(但保留条件的内容)。看来你是想用if
来过滤掉那个跑街区的孩子。当execl()
工作时,子程序不会在execl()
之后运行任何。我添加的printf和exit将不会运行。这些行只有在execl()
失败时才会运行,在这个简单的例子中,失败的唯一原因是您提供了不正确的参数。