我想通过按钮单击一个在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 <
}
// replace the child process with exec*-function
execv(program_call,args);
_exit(2);
}
else if (child == -1) // fork error
{
if (errno == EAGAIN)
{
cerr<
}
else if (errno == ENOMEM)
{
cerr<
}
}
else // parent process
{
usleep(50); // give some time
if ( errno == EACCES)
{
cerr<
}
else if ( errno == ENOENT)
{
cerr<
}
int child_status;
if ( waitpid(child, &child_status, WNOHANG | WUNTRACED) < 0) // waitpid failed
{
cerr<
}
else if ( WIFEXITED( child_status ) && WEXITSTATUS( child_status ) != 0)
{
cerr<
}
}
}
有两个问题:
关闭文件描述符会导致一些问题,例如Thunderbird崩溃或VLC运行时没有声音 . 更确切地说:关闭 stdout(1) 和 stderr(2) 会导致这些问题 . 据我所知,在exec之前关闭文件描述符只能防止它们被复制(不需要从子进程向父进程发送信息) . 为什么这会影响子进程?通过设置标志 FD_CLOEXEC 来替换 close() 不会改变任何内容 . 在fork之前设置 FD_CLOEXEC 标志也无法解决问题 . 有没有更好的方法来阻止文件描述符的继承?
waitpid的返回值通常为0,即使程序调用失败,我认为因为有两个(异步)进程 . usleep(50) 为我的需求解决了这个问题,但我希望有更好的解决方案来解决这个问题 .
我正在使用vfork,但使用fork会出现同样的问题 .