简体   繁体   English

在子进程中编写c ++

[英]writing in child process c++

I am trying to change a variable value inside a child process and keep it for the rest of the program. 我试图在子进程中更改变量值,并将其保留给程序的其余部分。 So In the below example why my cout keeps printing 0, and how do I solve it? 那么在下面的示例中,为什么我的cout总是打印0,如何解决呢?

int var = 0;
int pid = fork();

if (pid == 0){ //child process
   var = 1;
   exit(1);
}
else if (pid> 0){  //parent process
         if (-1 == wait (0))
              perror ("there was an error with wait");
}

cout << var;

This is how code execution is going to go. 这就是代码执行的方式。

Child Process 子进程

int var =0;

var = 1;
exit (1);

Parent Process 上级流程

int var =0;
if (-1 == wait (0))
  perror ("there was an error with wait);

cout << var;

So as you can see, var will not be changed for the parent process. 如您所见,对于父进程,不会更改var

When you fork , the child and parent have separate copies of the variables that were present before they split off into execution paths. 当您进行fork ,子级和父级在分离为执行路径之前,分别具有存在的变量副本。 Processes do not share the same block of memory. 进程不共享相同的内存块。 Therefore, altering var for the child will not affect the var in the parent. 因此,改变var的孩子会不会影响var父。

If you want multiple execution paths on the same piece of memory, you should use threads . 如果要在一块内存上使用多个执行路径,则应使用thread

Thank you for reading. 感谢您的阅读。

Looks like the fork() call has failed. 看起来fork()调用已失败。 Check the errno value 检查errno值

RETURN VALUE On success, the PID of the child process is returned in the parent, and 0 is returned in the child. 返回值成功后,将在父级中返回子进程的PID,在子级中返回0。 On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. 如果失败,则在父级中返回-1,不创建任何子级进程,并适当设置errno。

ERRORS EAGAIN fork() cannot allocate sufficient memory to copy the parent's page tables and allocate a task structure for the child. 错误EAGAIN fork()无法分配足够的内存来复制父级的页表并为子级分配任务结构。 EAGAIN It was not possible to create a new process because the caller's RLIMIT_NPROC resource limit was encountered. EAGAIN无法创建新进程,因为遇到了调用者的RLIMIT_NPROC资源限制。 To exceed this limit, the process must have either the CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability. 要超过此限制,该进程必须具有CAP_SYS_ADMIN或CAP_SYS_RESOURCE能力。 ENOMEM fork() failed to allocate the necessary kernel structures because memory is tight. 由于内存紧张,ENOMEM fork()无法分配必要的内核结构。

CONFORMING TO SVr4, 4.3BSD, POSIX.1-2001. 符合SVr4、4.3BSD,POSIX.1-2001。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM