DIFFERENT TASKS ASSIGNED TO DIFFERENT INSTANCES OF FORK() OF A PROCESS IN C

≡放荡痞女 提交于 2019-12-14 04:23:58

问题


Can I assign different task to different instances of fork() of a process in C ? like for example:

program.c has been forked 3 times

int main()
{
    pid_t pid;
    pid = fork();
    pid = fork();
    pid = fork();
}

now to every instance of fork() I want to do different thing, Can I do this? with forks ? or any other method if favorable? :)

PS: I am testing Real Time Linux and want to check the performance of the Context Switching through forks through Time Constraint.


回答1:


You can use posix process..

posix_spawn( &Pid,ProgramPath.c_str(), & FileActions,& SpawnAttr,argv,envp);

Check its documentation here.




回答2:


You always have to test the result of fork(2) (in particular, to handle error cases), and do different things for 0 result (successful in child process), positive result (successful in parent process), negative result (failure, so use perror). So according to that result you can do different things. Often you end up invoking execve(2) for the child process (when fork gives 0), and you usually setup things (e.g. for IPC thru pipe(7)-s) before calling fork.

So to assign a different task after a fork just execute different code according to result of fork

You should read Advanced Linux Programming. It has several chapters explaining all that (so I won't take the time to explain it here).

You could be interested in pthreads (implemented using clone(2) and futex(7), which you should not use directly unless you are implementing your thread library, which is not reasonable).

Try also to strace(1) several programs (including some shell and some basic commands). It will tell which syscalls(2) they are calling. See also intro(2).



来源:https://stackoverflow.com/questions/23196573/different-tasks-assigned-to-different-instances-of-fork-of-a-process-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!