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

Exec won't call my second program

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

coordinator.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
}

}

worker.c

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

  return 0;
}

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

看看这里了解函数的工作原理https://www.systutorials.com/docs/linux/man/3-execl/

假设工作人员 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);
}

如果工作人员在不同的目录中,则设置 PATH 变量,它似乎在同一目录中,因为您正在尝试执行 /worker 而不是 ./worker

编辑:

如何编译&执行:

coordinator.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
        }
}

worker.c

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

首先创建 worker executable/binary 为

gcc -Wall worker.c -o worker

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

gcc -Wall coordinator.c
./a.out