开发者

Convert call from spawn to fork-exec in C

开发者 https://www.devze.com 2023-03-18 10:17 出处:网络
I have code which looks like this in Linux: return_code= spawnp(cmd, 3, fd_map, NULL, argv, environ); I need to convert this from QNX to Linux - so I need to use fork-exec since spawn is not availa

I have code which looks like this in Linux:

return_code= spawnp(cmd, 3, fd_map, NULL, argv, environ);

I need to convert this from QNX to Linux - so I need to use fork-exec since spawn is not available in Linux. 1) How can that be done ? Is this right ?

pid = fork();
if (pid ==0) /* child */
    exec(cmd, argv, environ);

2) How do I pass the parameters fd_map and "3" which 开发者_如何学运维are passed in spawn to exec ?


I don't know what "3" does.

If you want to change the file descriptors available to the child process, you do not do this in the call to exec or fork, but you do it between by calling close, dup2, etc. The function posix_spawn basically does this for you, and on Linux/glibc, it is implemented using fork and exec (so you can read the source code...)

pid = fork();
if (!pid) {
    // close, dup2 go here
    exec(...);
    // error
}


The 3 indicates the number of file descriptors you are passing into the fd_map and in the spawnp() call it allows you to conveniently select only those file descriptors you want to pass along to the child process.

So after your call to fork() you will have all of the file descriptors in the child process so you can close out those file descriptors you aren't interested in and then, assuming that the file descriptors are not marked as CLOEXEC (close on exec) they will also carry through to the exec()'ed code.

Note that the fork() will fail however if your application is multi-threaded since, until recent versions, QNX doesn't support forking threaded processes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号