在Linux中,C++可以通过多种方式来进行进程管理。以下是一些常用的方法:
fork()和exec()fork()用于创建一个新的进程,而exec()系列函数用于在新进程中执行另一个程序。
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
execl("/bin/ls", "ls", "-l", (char *)NULL);
perror("execl");
return 1;
} else if (pid > 0) {
// 父进程
int status;
waitpid(pid, &status, 0);
printf("Child process exited with status %d
", WEXITSTATUS(status));
} else {
// fork失败
perror("fork");
return 1;
}
return 0;
}
system()system()函数可以执行一个shell命令。
#include <cstdlib>
int main() {
int ret = system("ls -l");
if (ret == -1) {
perror("system");
return 1;
}
return 0;
}
popen()popen()用于创建一个管道,并执行一个命令,可以通过管道读取命令的输出。
#include <cstdio>
#include <iostream>
int main() {
FILE* pipe = popen("ls -l", "r");
if (!pipe) {
perror("popen");
return 1;
}
char buffer[128];
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
std::cout << buffer;
}
pclose(pipe);
return 0;
}
fork()和wait()fork()创建子进程,wait()等待子进程结束。
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
execl("/bin/ls", "ls", "-l", (char *)NULL);
perror("execl");
return 1;
} else if (pid > 0) {
// 父进程
int status;
waitpid(pid, &status, 0);
printf("Child process exited with status %d
", WEXITSTATUS(status));
} else {
// fork失败
perror("fork");
return 1;
}
return 0;
}
pthread库虽然pthread主要用于线程管理,但也可以用于进程间通信和同步。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* thread_func(void* arg) {
printf("Thread is running
");
sleep(2);
printf("Thread is done
");
return NULL;
}
int main() {
pthread_t thread;
if (pthread_create(&thread, NULL, thread_func, NULL) != 0) {
perror("pthread_create");
return 1;
}
pthread_join(thread, NULL);
printf("Main thread is done
");
return 0;
}
std::process(C++20)C++20引入了std::process库,提供了更高级的进程管理功能。
#include <iostream>
#include <cstdlib>
#include <system_error>
#include <filesystem>
namespace fs = std::filesystem;
int main() {
try {
auto result = std::system("ls -l");
if (result != 0) {
throw std::system_error(result, std::generic_category(), "Command failed");
}
} catch (const std::system_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}
system()时要小心,因为它会执行传入的字符串,可能会受到shell注入攻击。通过这些方法,你可以在C++程序中有效地进行进程管理。