使用VIM编写c源文件,由父进程创建一个子进程,父子进程分别输出自己的进程号。
用fork函数控制进程 调用ls去显示指定目录下的文件信息。
基于new bing的建议:
打开终端,使用vim创建一个c源文件,例如test.c,命令为:
vim test.c
在test.c中编写代码,内容如下:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
printf("fork error\n");
exit(1);
} else if (pid == 0) {
printf("child process: pid = %d\n", getpid());
} else {
printf("parent process: pid = %d\n", getpid());
}
execl("/bin/ls", "ls", "/home/", NULL);
return 0;
}
这段代码首先使用fork()函数创建一个子进程,然后根据返回值判断当前是在父进程还是在子进程中,并分别输出自己的进程号。最后使用execl()函数调用ls命令去显示指定目录下的文件信息。
编译并运行程序,命令为:
gcc -o test test.c
./test
这样就可以在终端中看到父子进程的进程号以及ls命令输出的指定目录下的文件信息了。
希望能对你有帮助!