Lex*_*exa 5 c linux fork file-descriptor exec
我想通过按钮单击一个在linux中运行程序,因此我编写了一个函数execute:
void execute(const char* program_call, const char* param )
{
pid_t child = vfork();
if(child == 0) // child process
{
int child_pid = getpid();
char *args[2]; // arguments for exec
args[0] = (char*)program_call; // first argument is program_call
args[1] = (char*)param;
// close all opened file descriptors:
const char* prefix = "/proc/";
const char* suffix = "/fd/";
char child_proc_dir[16];
sprintf(child_proc_dir,"%s%d%s",prefix,child_pid, suffix);
DIR *dir;
struct dirent *ent;
if ((dir = opendir (child_proc_dir)) != NULL) {
// get files and directories within directory
while ((ent = readdir (dir)) != NULL) {
// convert file name to int
char* end;
int fd = strtol(ent->d_name, &end, 32);
if (!*end) // valid file descriptor
{
close(fd); // close file descriptor
// or set the flag FD_CLOEXEC
//fcntl( fd, F_SETFD, FD_CLOEXEC );
}
}
closedir (dir);
}
else
{
cerr<< "can not open directory: " << child_proc_dir <<endl;
}
// replace the child process with exec*-function
execv(program_call,args);
_exit(2);
}
else if (child == -1) // fork error
{
if (errno == EAGAIN)
{
cerr<<“To much processes"<<endl;
}
else if (errno == ENOMEM)
{
cerr<<“Not enough space available."<<endl;
}
}
else // parent process
{
usleep(50); // give some time
if ( errno == EACCES)
{
cerr<<“Permission denied or process file not executable."<<endl;
}
else if ( errno == ENOENT)
{
cerr<<"\n Invalid path or file."<<endl;
}
int child_status;
if ( waitpid(child, &child_status, WNOHANG | WUNTRACED) < 0) // waitpid failed
{
cerr<<"Error - Execution failed"<<endl;
}
else if ( WIFEXITED( child_status ) && WEXITSTATUS( child_status ) != 0)
{
cerr<<“Child process error - Execution failed"<<endl;
}
}
}
Run Code Online (Sandbox Code Playgroud)
有两个问题:
关闭文件描述符会导致一些问题,例如Thunderbird崩溃或VLC运行时没有声音.更确切地说:关闭stdout(1)并stderr(2)导致这些问题.据我所知,在exec之前关闭文件描述符只能防止它们被复制(不需要从子进程向父进程发送信息).为什么这会影响子进程?close()通过设置标志来替换FD_CLOEXEC不会改变任何东西.FD_CLOEXEC在fork之前设置标志也无法解决问题.有没有更好的方法来阻止文件描述符的继承?
waitpid的返回值通常为0,即使程序调用失败,我认为因为有两个(异步)进程.usleep(50)为我的需求解决了这个问题,但我希望有更好的解决方案来解决这个问题.
我正在使用vfork,但使用fork会出现同样的问题.
首先,在 2014 年,永远不要使用vfork而只是fork(2)。(因为vfork(2)自 POSIX 2001 起已过时,并在 POSIX 2008 中被删除)。
然后,关闭大部分文件描述符的最简单方法就是
for (int fd=3; fd<256; fd++) (void) close(fd);
Run Code Online (Sandbox Code Playgroud)
(提示:如果 afd无效,close(fd)则会失败,我们忽略该失败;并且您从3保持打开 0== stdin、 1== stdout、 2== stderr开始;所以原则上以上所有内容 close都会失败)。
然而,行为良好且编写良好的程序在关闭时不需要这样的循环(因此这是克服以前的错误的粗略方法)。
当然,如果您知道除 stdin、stdout、stderr 之外的某些文件描述符是有效的并且子级需要它program_call(这不太可能),您将需要显式跳过它。
然后FD_CLOEXEC尽可能多地使用。
您的程序不太可能在您不知情的情况下拥有大量文件描述符。
也许您想要daemon(3)或(如vality所评论)posix_spawn。
如果您需要显式关闭STDIN_FILENO(即 0)、或STDOUT_FILENO(即 1)或STDERR_FILENO(即 2),您最好open("/dev/null",...以及dup2它们之后 - 调用之前exec,因为大多数程序都希望它们存在。
| 归档时间: |
|
| 查看次数: |
9146 次 |
| 最近记录: |