java 关闭子进程吗_为什么在fork之后关闭文件描述符会影响子进程?

我想通过按钮单击一个在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会出现同样的问题 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值