forked from templates/base
39 lines
1.0 KiB
C
39 lines
1.0 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <sys/wait.h>
|
|
|
|
int main(int argc, char *argv[])
|
|
{
|
|
(void)argc; // 明确标记未使用
|
|
(void)argv; // 消除编译器警告
|
|
|
|
pid_t pid = fork(); // 使用pid_t类型更规范
|
|
|
|
if (pid < 0) {
|
|
/* 错误处理 */
|
|
perror("Fork Failed");
|
|
exit(EXIT_FAILURE); // 使用标准失败码
|
|
}
|
|
else if (pid == 0) {
|
|
/* 子进程 */
|
|
execlp("/bin/ls", "ls", (char *)NULL); // 确保NULL转换为(char *)
|
|
|
|
// 如果exec失败才会执行到这里
|
|
perror("Exec Failed");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
else {
|
|
/* 父进程 */
|
|
int status;
|
|
wait(&status); // 获取子进程退出状态
|
|
|
|
if (WIFEXITED(status)) {
|
|
printf("Child Completed with status: %d\n", WEXITSTATUS(status));
|
|
} else {
|
|
printf("Child terminated abnormally\n");
|
|
}
|
|
|
|
exit(EXIT_SUCCESS); // 使用标准成功码
|
|
}
|
|
} |