Yes, you can. Defining the right list of posix spawn file actions definitely is the way to go.
Example:
#include <errno.h>
#include <fcntl.h>
#include <spawn.h>
#include <stdio.h>
#include <string.h>
#define CHECK_ERROR(R, MSG) do { if (R) { fprintf(stderr, "%s: %s\n",
(MSG), strerror(R)); return 1; } } while (0)
extern char **environ;
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "Call: %s OUTFILE COMMAND [ARG]...\n", argv[0]);
return 2;
}
const char *out_filename = argv[1];
char **child_argv = argv+2;
posix_spawn_file_actions_t as;
int r = posix_spawn_file_actions_init(&as);
CHECK_ERROR(r, "actions init");
r = posix_spawn_file_actions_addopen(&as, 1, out_filename,
O_CREAT | O_TRUNC | O_WRONLY, 0644);
CHECK_ERROR(r, "addopen");
r = posix_spawn_file_actions_adddup2(&as, 1, 2);
CHECK_ERROR(r, "adddup2");
pid_t child_pid;
r = posix_spawnp(&child_pid, child_argv[0], &as, NULL,
child_argv, environ);
CHECK_ERROR(r, "spawnp");
r = posix_spawn_file_actions_destroy(&as);
CHECK_ERROR(r, "actions destroy");
return 0;
}
Compile and test:
$ cc -Wall -g -o spawnp spawnp.c
$ ./spawnp log date -I
$ cat log
2018-11-03
$ ./a.out log dat
spawnp: No such file or directory
Note that the posix_spawn
functions don't set errno, instead, unlike most other UNIX functions, they return an error code. Thus, we can't use perror()
but have to use something like strerror()
.
We use two spawn file actions: addopen and addup2. The addopen is similar to a normal open()
but you also specify a file descriptor which is automatically closed if already open (here 1, i.e. stdout). The addup2 has similar effects to dup2()
, i.e. the target file descriptor (here 2, i.e. stderr) is atomically closed before 1 is duplicated to 2. Those actions are only executed in the child created by posix_spawn
, i.e. right before it execs the specified command.
Like fork()
, posix_spawn()
and posix_spawnp()
immediately return to the parent. Thus, we have to use waitid()
or waitpid()
to explicitly wait on child_pid
's termination.
posix_spwan
is a pointer of typeposix_spawn_file_actions_t
(one you have given asNULL
).posix_spawn
will open, close or duplicate file descriptors inherited from the calling process as specified by theposix_spawn_file_actions_t
object. Theposix_spawn_file_actions_{addclose,adddup2}
functions are used to indicate what happens to which fd.