【发布时间】:2012-03-26 20:06:25
【问题描述】:
我需要创建一个函数,除其他外,它会产生一个子进程。 我想向这个函数传递一个可选的文件描述符列表,以便根据用户需要重定向子进程的输入/输出。
我看到很多人谈论如何使用dup2 来做到这一点,有点像这样:
if( pid < 0 ) // error forking.
{
//...
}
else if( pid != 0 ) // Parent process.
{
ret = waitpid( pid, &status, 0 );
return WEXITSTATUS( status );
}
else // Child process.
{
dup2( fd, STDIN_FILENO ); // Clone passed file discriptor.
close( fd ); // Close the passed one, since we have already cloned.
execvp( arglist[ 0 ], arglist );
}
好的。所有这些都在互联网上。
我现在的问题是,如何(或最好的方式)重定向到/dev/null?
我应该强制用户open( /dev/null) 并将其传递为fd 还是有更好的方法?
编辑:
这并不像我想要的那样漂亮,但我找不到更好的方法,所以我最终将一个文件名数组传递到用户想要重定向的任何地方,分别是 STDIN、STDOUT 和 STDERR:
static int do_exec( arglist_t arglist, const char *fio[ 3 ] )
{
DEBUG__( OSU_DEBUG_LEVEL_1, "fio = %p\n", fio );
if ( fio )
{
if ( fio[ STDIN_FILENO ] )
{
int fd = open( fio[ STDIN_FILENO ], O_RDONLY );
if ( -1 < fd )
{
dup2( fd, STDIN_FILENO );
close( fd );
}
}
if ( fio[ STDOUT_FILENO ] )
{
int fd = open( fio[ STDOUT_FILENO ], O_WRONLY | O_CREAT | O_APPEND );
if ( -1 < fd )
{
dup2( fd, STDOUT_FILENO );
close( fd );
}
}
if ( fio[ STDERR_FILENO ] )
{
int fd = open( fio[ STDERR_FILENO ], O_WRONLY | O_CREAT | O_APPEND );
if ( -1 < fd )
{
dup2( fd, STDERR_FILENO );
close( fd );
}
}
}
return execvp( arglist[ 0 ], arglist );
}
- 我还没有完全测试它,所以它可能有一些错误。
非常感谢@Zack 和@gbulmer。
【问题讨论】:
标签: c linux process fork embedded-linux