c - 使用 fork() 系统调用创建 6 个孩子
问题描述
我正在尝试编写一个程序来创建 6 个具有 fork 系统调用的孩子,每个孩子都运行 /bin/ls 具有不同类型的 exec() 函数的命令,当所有孩子完成他们的工作时,父母应该打印出它的 pid。仍然使用此代码给出错误的输出:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
printf("hello world (pid:%d)\n", (int) getpid());
for (int i =0 ; i<6;i++)
{
char *myargs_path = "/bin/ls";
char *myargs_file[2] = {"ls",NULL};
char *myargs_temp[2] = {"done",NULL};
if (fork() == 0)
{
if (i == 0)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execl(myargs_path,myargs_path,NULL);
}
if (i == 1)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execlp(myargs_file[0],myargs_file[0],NULL);
}
if (i == 2)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execle(myargs_path,myargs_path,NULL,myargs_temp);
}
if (i == 3)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execv(myargs_path,myargs_path);
}
if (i == 4)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execvp(myargs_file[0],myargs_file[0]);
}
if (i == 5)
{
printf("hello, I am child (pid:%d)\n", (int) getpid());
execvpe(myargs_file[0],myargs_file,myargs_temp);
}
}
}
for(int i=0;i<6;i++)
{
int wc = wait(NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",wc, wc, (int) getpid());
}
return 0;
}
解决方案
你有一些不正确的论点。你要:
switch(i) {
case 0: execl(myargs_path, myargs_path, NULL);
break;
case 1: execlp(myargs_file[0], myargs_file[0], NULL);
break;
case 2: execle(myargs_path, myargs_path, NULL, myargs_temp);
break;
case 3: execv(myargs_path, myargs_file);
break;
case 4: execvp(myargs_file[0], myargs_file);
break;
case 5: execvpe(myargs_file[0], myargs_file, myargs_temp);
break;
}
推荐阅读
- reactjs - wrapper.find 由于连接而无法正常工作
- amazon-web-services - 如何衡量每个用户(客户)使用的出站数据
- javascript - 如何更改下拉列表中的选定值
- flutter - Stack 中的 ModalBarrier 不会触发 GestureDetector
- unity3d - Unity 中的地形纹理
- python - 从 Musixmatch 中检索歌词
- android - withContext 协程不工作。在 Android 中使用 Kotlin
- javascript - 待办事项列表应用程序 - ReactJS 上的 onChange 不起作用?
- c# - 如果 EF 导航属性具有默认值,则不会加载它们
- mysql - InnoDB 初始化警告