Exec不会拨打我的第二个程序

时间:2018-01-28 00:13:30

标签: c linux fork exec parent-child

我创建了一个测试文件,看看我是否可以运行第二个程序,但代码不会运行实际文件,即使它似乎在编译。我的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;
}

2 个答案:

答案 0 :(得分:3)

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

点击此处了解该功能的工作原理https://www.systutorials.com/docs/linux/man/3-execl/

答案 1 :(得分:2)

假设工作人员executablemain(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变量,它似乎在同一目录中,因为您尝试./worker而不是#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 } }

编辑:

如何编译&amp;执行:

<强> coordinator.c

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

<强> worker.c

worker

首先将gcc -Wall worker.c -o worker 可执行文件/二进制文件创建为

main

接下来,创建gcc -Wall coordinator.c ./a.out 可执行文件并运行它

index.map(custom_function)
相关问题