我正在編寫一個簡單的C程序來創建我自己的shell。它將輸入作爲命令並執行它們。但是當我嘗試在後臺執行一個進程時(也就是說,我從父進程派生一個進程,父進程不會等待子進程完成,而是在子進程在後臺運行時繼續執行更多輸入命令。 )execvp會執行命令,但會立即發出分段錯誤。 你能幫我嗎?我將發佈我認爲相關的代碼的一部分。如果您需要了解更多信息,請告知我,我會相應地編輯我的問題。C程序shell:Execvp打印輸出,然後在執行後臺進程時發生分段錯誤
while(1){
pid = fork();
if(pid == 0)
executeCommand(info);
else
{
if(info->boolBackground ==1)
{
waitpid(pid , status , WNOHANG);
}
else
wait(NULL);
}
} //Info contains the command to be executed and it's arguments.
這裏是我executeCommand功能:
void executeCommand(parseInfo * info)
{
FILE *infile, *outfile;
struct commandType * com;
char * cmd;
int i , status;
cmd = (char*)malloc(1024);
strcpy(cmd , info->CommArray[0].command);
if(info->boolOutfile == 1)
{
outfile = fopen(info->outFile, "w");
dup2(fileno(outfile), 1);
}
if(info->boolInfile == 1)
{
infile = fopen(info->inFile, "r");
dup2(fileno(infile), 0);
}
status = execvp(cmd , info->CommArray[0].VarList); //VarList contains the arguments
if(status == -1){
printf("%s\n",strerror(errno));}
exit(0);
}
當我給一個輸入命令:ls & (&意味着LS應在背景中執行。) ,它派生一個子進程,其執行ls並打印目錄中的文件/目錄列表,然後給出分段錯誤。你能發現錯誤嗎?我試着用簡單的ls命令在後臺運行execvp。它也導致分段錯誤。
如果status不是指針,那麼在'waitpid'調用中,您可能需要'''status'。 –