2017-09-13 71 views
0

我想写一个程序,将叉,然后打开一个文件并执行它。它应该执行的文件被称为child,并且它已经被编译。当我输入./child时,它会运行。但是,当我运行此程序时,它不执行子程序,并提示我输入“执行失败”的错误消息。我做错了什么?无法获得execvp来执行文件

这是我的父类

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/wait.h> 



int main (int argc, char **argv) 
{ 

pid_t parent = getpid(); 
pid_t pid = fork(); 


if (pid == -1) 
{ 
// error, failed to fork() 
} 
else if (pid > 0) 
{ 
int status; 
waitpid(pid, &status, 0); 
} 
else 
{ 

int var = execvp("./child", NULL); 

if(var < 0) 
{ 
    printf("Execution failed"); 
} 

} 
exit(0); // exec never returns 
} 

这是孩子

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 


int main (int argc, char **argv) 
{ 
printf ("Im the child"); 
exit (0); 
} 
+2

1.请仔细阅读文档。 2.打印'errno',如果可能'strerror(errno)',它说什么? 3.你为什么认为'./ child'应该被传递给'execvp()'? 3.第二个参数应该是什么? 4.您是否阅读过文档?我不认为你这样做,因为你会知道第二个参数应该是什么。不要太坏,但请在提问前阅读文档。 –

+1

它可以是可以改进的(编译器对于主...的很多警告),但对我来说代码起作用。 –

+0

你能想到为什么它不适合我的任何原因吗?子程序从不执行。 – Rubiks

回答

1

其实我不知道你在做什么错。复制和编译(和几个警告投诉)后,您的代码运行良好(GCC 7.2)。

很显然,孩子必须位于运行主可执行文件(分叉的那个)的同一个工作目录中。

,不过也许我会写这样的代码,但我不是一个专家在分叉:

#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <sys/wait.h> 
#include <errno.h> 

extern int errno; 

int main() { 
    pid_t pid = fork(); 

    if (pid < 0) { 
    fprintf(stderr, "%s\n", strerror(errno)); 
    return 1; 
    } 

    if (pid == 0) { 
    int ret = execl("./child", "", (char *)NULL); 
    if(ret < 0) { 
    fprintf(stderr, "%s\n", strerror(errno)); 
    return 1; 
    } 
    } else { 
    wait(NULL); 
    } 
    return 0; 
} 

至少它告诉你错误execl遇到哪些。