在Linux中,可以使用fork()和exec()系統調用來創建一個Bash子進程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork(); // 創建子進程
if (pid == 0) { // 子進程
char *argv[] = {"bash", "-c", "echo 'Hello from the child process!'", NULL};
execvp(argv[0], argv); // 在子進程中執行Bash命令
perror("execvp"); // 如果execvp()失敗,打印錯誤信息
exit(EXIT_FAILURE); // 退出子進程
} else if (pid > 0) { // 父進程
int status;
waitpid(pid, &status, 0); // 等待子進程完成
printf("Child process finished with status %d\n", WEXITSTATUS(status));
} else { // fork()失敗
perror("fork"); // 打印錯誤信息
exit(EXIT_FAILURE); // 退出父進程
}
return 0;
}
gcc -o create_child_process create_child_process.c
./create_child_process
這個程序將創建一個子進程,并在其中執行echo 'Hello from the child process!'命令。父進程將等待子進程完成,并打印子進程的退出狀態。