【发布时间】:2020-02-27 07:24:27
【问题描述】:
两个示例输出(由我的教授提供)是(在 Linux 终端中输入):
ibrahim@ibrahim-latech:~$ ./prog2 .
Current working directory: /home/ibrahim
Executing ls . --all -l --human-readable
total 24M
drwxr-xr-x 74 ibrahim ibrahim 20K Oct 26 16:08 .
drwxr-xr-x 6 root root 4.0K Apr 10 2014 ..
-rw-r--r-- 1 ibrahim ibrahim 4.1K Sep 13 12:09 .bashrc
drwxr-xr-x 7 ibrahim ibrahim 4.0K Oct 11 14:51 Desktop/
...snip...
Exit status: 0
如果代码有效,则退出状态为 0,但此示例:
ibrahim@ibrahim-latech:~$ ./prog2 /root
Current working directory: /home/ibrahim
Executing ls /root --all -l --human-readable
Can't chdir to /root
Exit status: 1
退出状态为1,因为它是假的。
这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
pid_t pid;
pid = fork();
char cwd[255];
if(pid == 0){
printf("Current working directory: %s\n",getcwd(cwd, sizeof(cwd)));
printf("Executing ls %s --all -l --human-readable\n",argv[1]);
if(chdir(argv[1])!=0){
printf("this is not a valid directory");
}
else{
execl("/bin/ls","ls","--all","-l","--human-readable", NULL);
}
}
else{
wait(NULL):
printf("Exit status:");// not sure how to put the 1 or 0 in this
}
}
退出状态必须从父进程输出。我不知道如何让退出状态起作用。
【问题讨论】: