linux复制新的文件描述符,在Linux中创建新线程复制文件描述符和套接字描述符?...

线程共享相同的内存,所以它们共享相同的变量.如果在父线程中关闭套接字,它也将在子线程中关闭.

编辑:

man fork:小孩继承父系列的打开文件描述符的副本.

> man pthreads:线程共享一系列其他属性(即这些属性是进程范围而不是每个线程):[…]打开文件描述符

和一些代码:

#include

#include

using namespace std;

#include

#include

#include

#include

// global variable

int fd = -1;

void * threadProc(void * param) {

cout << "thread: begin" << endl;

sleep(2);

int rc = close(fd);

if (rc == -1) {

int errsv = errno;

cout << "thread: close() failed: " << strerror(errsv) << endl;

}

else {

cout << "thread: file is closed" << endl;

}

cout << "thread: end" << endl;

}

int main() {

int rc = open("/etc/passwd", O_RDONLY);

fd = rc;

pthread_t threadId;

rc = pthread_create(&threadId, NULL, &threadProc, NULL);

sleep(1);

rc = close(fd);

if (rc == -1) {

int errsv = errno;

cout << "main: close() failed: " << strerror(errsv) << endl;

return 0;

}

else {

cout << "main: file is closed" << endl;

}

sleep(2);

}

输出为:

thread: begin

main: file is closed

thread: close() failed: Bad file descriptor

thread: end

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值