首页 > 解决方案 > 使用 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;
}

标签: cforkexec

解决方案


你有一些不正确的论点。你要:

                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;
                }

推荐阅读