代码之家  ›  专栏  ›  技术社区  ›  noel880

Exec不会调用我的第二个程序

  •  0
  • noel880  · 技术社区  · 8 年前

    我创建了一个测试文件,看看是否可以运行第二个程序,但代码并没有运行实际的文件,即使它看起来是编译的。我的exec语法是否不正确?

    协调员c

    int main(int argc, char *argv[])
    {
    
    // Creates 2^n processes for n amount of values.
    pid_t child = fork();
    
    if(child < 0) //parent process
    {
        perror("fork() system call failed.");
        exit(-1);
    }
    
    else if(child == 0) //Child Process, worker will be called here.
    {
         execl("/worker", "worker", "Hello", NULL);
         printf("I'm the child %d, my parent is %d\n", getpid(), getpid());  
    }
    else
    {
        printf("I'm the parent %d, my child is %d\n", getpid(), child);
        wait(NULL); // wait for child process to catch up
    }
    
    }
    

    工人c

    int main(int argc, char *argv[])
    {
      printf("Hi, I'm the worker file!");
    
      return 0;
    }
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Andrea Tulimiero    8 年前

    问题在于 PATH 你要传递给的论点 execl() . 事实上,如果您插入 / 在作为第一个参数传递的字符串的开头,函数将在文件系统的根目录下查找程序。 让它去寻找 工人 可在当前目录中执行,只需指定其名称 execl("worker", ... ) execl("./worker", ... )

    查看此处以了解函数的工作原理 https://www.systutorials.com/docs/linux/man/3-execl/

        2
  •  2
  •   Achal    8 年前

    比如说工人 executable 位于运行 main(coordinator) 处理然后输入 child process 执行时 exec 你应该这样做 ./worker 而不是 /worker ,显示当前工作目录。

    请参见手册页,共页 exec() 对于其他论点,它说

    int execl(const char *path, const char *arg, ...);
    

    子进程应如下所示

    else if(child == 0) //Child Process, worker will be called here.
    {
         printf("I'm the child %d, my parent is %d\n", getpid(), getpid());
         //execl("/worker", "worker", "Hello", NULL);/** It's wrong, check the below one **/
         execl("./worker", "./worker", NULL);
    }
    

    如果worker位于不同的目录中,则设置PATH变量,因为您正在尝试 /工人 而不是 ./工人 .

    编辑:

    如何编译(&A);执行:

    协调员c

    #include<unistd.h>
    #include<stdio.h>
    #include<stdlib.h>
    int main(int argc, char *argv[])
    {
            pid_t child = fork();
            if(child < 0){
                    perror("fork() system call failed.");
                    exit(-1);
            }
            else if(child == 0) {
                    printf("I'm the child %d, my parent is %d\n", getpid(), getpid());
                    execl("./worker", "./worker", NULL);
            }
            else {
                    printf("I'm the parent %d, my child is %d\n", getpid(), child);
                    wait(NULL); // wait for child process to catch up
            }
    }
    

    工人c

    int main(int argc, char *argv[])
    {
            printf("Hi, I'm the worker file!");
            return 0;
    }
    

    首先创建 worker 可执行/二进制组件

    gcc -Wall worker.c -o worker
    

    接下来,创建 main 可执行文件并运行它

    gcc -Wall coordinator.c
    ./a.out