我正在学习等待和分叉函数,我试图打印出父进程和子进程的总和,但由于某种原因,总和似乎在父进程中重新初始化为零,我也没有确定我实现等待函数的方式,因为我可以在网上找到的所有资源都是用 c 语言而不是 c++ 语言。
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
int Sum = 0;
void printout()
{
int id = fork();
if(id!=0)
{
wait(NULL);
}
if(id == 0)
{
Sum += 2;
}
if(id!= 0)
{
Sum += 3;
}
}
int main()
{
printout();
std::cout<<Sum<<std::endl;
}
我期待的输出:
5
但我得到的输出为:
2
3
您面临的问题是因为
fork()
系统调用创建了一个新的子进程,它是父进程的精确副本,包括其变量和内存。然而,子进程和父进程拥有独立的内存空间。这意味着当您在子进程中修改 Sum
变量时,不会影响父进程中的 Sum
变量,反之亦然。
在您的代码中,父进程和子进程都有自己单独的
Sum
变量副本,并且它们正在递增各自的副本。当您在 Sum
函数中打印 main
时,您只是打印父进程中 Sum
变量的值。
如果您想获得父进程和子进程中修改的值的总和,可以使用进程间通信(IPC)机制,例如管道或共享内存。
例如使用管道:
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
int main() {
int Sum = 0;
int pipe_fd[2]; // Create a pipe for communication
if (pipe(pipe_fd) == -1) {
perror("pipe");
return 1;
}
int id = fork();
if (id == -1) {
perror("fork");
return 1;
}
if (id == 0) { // Child process
close(pipe_fd[0]); // Close the read end of the pipe in the child process
int childSum = 2;
write(pipe_fd[1], &childSum, sizeof(childSum)); // Write childSum to the pipe
close(pipe_fd[1]); // Close the write end of the pipe in the child process
} else { // Parent process
close(pipe_fd[1]); // Close the write end of the pipe in the parent process
read(pipe_fd[0], &Sum, sizeof(Sum)); // Read the child's value from the pipe
close(pipe_fd[0]); // Close the read end of the pipe in the parent process
Sum += 3; // Modify the Sum in the parent process
wait(NULL);
std::cout << Sum << std::endl; // Output the final sum
}
return 0;
}