首页 > 解决方案 > 如何在c中使用子进程

问题描述

fork(). 我从另一个终端看到它们仍然处于活动状态,直到我执行退出成功。例如,如果我想说:我想让 pid 为 10243 的子进程,目前处于活动状态,请执行此方法。我想在所有孩子都初始化之后调用该方法,所以在fork之后。我必须打字execvp ()吗? execvp (methodName (a))?

编辑:我会尝试添加一个类似的代码,以便更具体

所以假设我做了一个循环,我创建了 n 个孩子

            
        switch (pid = fork()) {     
            case -1:
                /* Handle error */
                fprintf(stderr, "%s, %d: Errore (%d) nella fork\n",
                __FILE__, __LINE__, errno);
                exit(EXIT_FAILURE);
            case 0: 

                    //here I have saved the pid of the child process        
                
            break;
            
        
            default:

            /* PARENT CODE: nothing here */
            wait(NULL);     
            exit(0);            

            break;
        }
    }```

So at that point I have created n number of child process. Now I want, for example, that the child with the pid 10342 do a method called "method1()", and the child with the pid 10343 do a method called "method2()".

How can I say that? Is that possibile? Because I need first to create all the child and then use them while the "main process" is in stand by with an infinte cycle. Like: 

```int u = 0;
    while(u == 0){         I will handle the end of this with a signal 
        
        }
    }
exit(EXIT_SUCCESS);

标签: cprocessforkexecvp

解决方案


fork的手册页:

子进程和父进程在不同的内存空间中运行。在 fork() 时,两个内存空间具有相同的内容。

这意味着,内存中的所有函数都可以被父进程和子进程调用,但是没有办法,一个进程可以调用驻留在另一个进程的内存空间中的函数。

为此,您需要 IPC(进程间通信)。

附录

在 fork 之后,您可以运行您喜欢的每个功能(在子进程中 - 我希望您知道这意味着什么,如果没有,提供的链接将帮助您)。但是只有通过 IPC 才能“使”子进程处于活动状态并运行某种方法。


推荐阅读