c - 使用 execlp() 运行 C 程序?

标签 c linux process exec fork

所以我有一个名为“hello.c”的 c 程序,它除了最后的“exit(2)”之外什么都不做。我尝试在我的子进程中运行它,然后将返回值传递给我的父进程并打印相应的消息。但不知何故,程序总是在 0 处退出并打印“在 0 处退出”消息。谁能告诉我为什么?

pid_t pid;
int status;

pid = fork(); 

if (pid == -1){
    perror("fork");
    exit(1);
} 
if (pid >0){
    /*abusive parents*/
    waitpid(pid, &status, 0);

    if(WEXITSTATUS(status)==3){
        printf("exit at 3\n");
    }
    if(WEXITSTATUS(status)==2){
        printf("exit at 2\n");
    }
    if(!(WEXITSTATUS(status))){
        printf("exit at 0\n");
    }

}
else{
    /*stupid child*/
    execlp("hello.c",NULL);
}


return 0;}

这是 hello.c:

int main(void){
   int teemo=0;

   exit(2);
}

最佳答案

你不能运行一个C源文件,你需要编译(和链接)它生成一个可执行文件,然后运行这个文件。因此,你应该做类似的事情

  1. 首先编译hello.c(我想你正在使用gcc)

    gcc -o hello hello.c
    
  2. 在你的第一个程序中运行 hello

    execlp("./hello", "hello", NULL);
    

然后你应该得到你所期望的。

关于c - 使用 execlp() 运行 C 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22139996/

相关文章:

c# - 使用环境变量启动进程

c - PROCESS SYSTEM CALL中PID的变量类型是什么?

c - 为什么我会收到 "corrupted double-linked list"错误?

c - 不使用循环打印 1 到 1000

c - Valgrind “invalid write/read of size 1” 错误 memcpy

c - 如何使用 scanf() 获取 int

Linux,su,在远程 session 上禁用指纹验证

linux - 使用 SED/Perl 删除字符并删除空行

php - 升级到 Debian Jessie 后 : Random mod_fcgid errors

java - 如何更改优先流程