在Linux系统中,主要有以下几种创建进程的方式:
#include <unistd.h>
pid_t fork(void);
#include <unistd.h>
pid_t vfork(void);
#include <unistd.h>
int execl(const char *path, const char *arg, ...);
int execv(const char *path, char *const argv[]);
int execle(const char *path, const char *arg, ..., char *const envp[]);
int execve(const char *path, char *const argv[], char *const envp[]);
int execlp(const char *file, const char *arg, ...);
int execvp(const char *file, char *const argv[]);
#include <stdlib.h>
int system(const char *command);
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
#include <stdlib.h>
void exit(int status);
void _Exit(int status);
#include <unistd.h>
void _exit(int status);
#include <stdlib.h>
void abort(void);
父进程通常需要等待子进程终止:
#include <sys/wait.h>
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
signal(SIGCHLD, SIG_IGN);
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid == 0) {
// 子进程
printf("Child process (PID: %d)\n", getpid());
execlp("/bin/ls", "ls", NULL);
} else {
// 父进程
printf("Parent process (PID: %d), Child PID: %d\n", getpid(), pid);
wait(NULL);
printf("Child complete\n");
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
printf("Child process running...\n");
sleep(2);
printf("Child process exiting\n");
exit(0); // 子进程正常退出
} else if (pid > 0) {
// 父进程
printf("Parent waiting for child...\n");
wait(NULL); // 等待子进程结束
printf("Parent detected child exit\n");
} else {
perror("fork failed");
exit(1);
}
return 0;
}
通过合理使用这些进程创建和销毁机制,可以构建高效、稳定的Linux应用程序。