高级I/O函数之socketpair和dup/dup2

1、socketpair函数

     pipe用来创建管道,但是的单个管道只能单向通信,一端进行读,另一端进行写。如果要实现进程双向通信,必须创建一对管道,而socketpair则可以用来创建双向通信的管道。

      socketpair创建了一对匿名的套接字描述符(只能在AF_UNIX域中使用),描述符存储于一个二元数组。eg: s[2] 这对套接字可以进行双工通信,每一个描述符既可以读也可以写。这个在同一个进程中也可以进行通信,向s[0]中写入,就可以从s[1]中读取(只能从s[1]中读取),也可以在s[1]中写入,然后从s[0]中读取;但是,若没有在0端写入,而从1端读取,则1端的读取操作会阻塞,即使在1端写入,也不能从1读取,仍然阻塞;反之亦然。

函数原型如下:


      socketpair函数的前三个参数的含义与socket系统调用的三个参数完全相同。socketpair的

int logwrap_fork_execvp(int argc, const char* const* argv, int* status, bool forward_signals, 534 int log_target, bool abbreviated, const char* file_path) { 535 pid_t pid; 536 int parent_ptty; 537 sigset_t oldset; 538 int rc = 0; 539 540 rc = pthread_mutex_lock(&fd_mutex); 541 if (rc) { 542 ERROR("failed to lock signal_fd mutex\n"); 543 goto err_lock; 544 } 545 546 /* Use ptty instead of socketpair so that STDOUT is not buffered */ 547 parent_ptty = TEMP_FAILURE_RETRY(posix_openpt(O_RDWR | O_CLOEXEC)); 548 if (parent_ptty < 0) { 549 ERROR("Cannot create parent ptty\n"); 550 rc = -1; 551 goto err_open; 552 } 553 554 char child_devname[64]; 555 if (grantpt(parent_ptty) || unlockpt(parent_ptty) || 556 ptsname_r(parent_ptty, child_devname, sizeof(child_devname)) != 0) { 557 ERROR("Problem with /dev/ptmx\n"); 558 rc = -1; 559 goto err_ptty; 560 } 561 562 if (forward_signals) { 563 // Block these signals until we have the child pid and our signal handlers set up. 564 block_signals(&oldset); 565 } 566 567 pid = fork(); 568 if (pid < 0) { 569 ERROR("Failed to fork\n"); 570 rc = -1; 571 goto err_fork; 572 } else if (pid == 0) { 573 pthread_mutex_unlock(&fd_mutex); 574 if (forward_signals) { 575 unblock_signals(&oldset); 576 } 577 578 setsid(); 579 580 int child_ptty = TEMP_FAILURE_RETRY(open(child_devname, O_RDWR | O_CLOEXEC)); 581 if (child_ptty < 0) { 582 FATAL_CHILD("Cannot open child_ptty: %s\n", strerror(errno)); 583 } 584 close(parent_ptty); 585 586 dup2(child_ptty, 1); 587 dup2(child_ptty, 2); 588 close(child_ptty); 589 590 child(argc, argv); 591 } else { 592 if (forward_signals) { 593 setup_signal_handlers(pid); 594 unblock_signals(&oldset); 595 } 596 597 rc = parent(argv[0], parent_ptty, pid, status, log_target, abbreviated, file_path, 598 forward_signals); 599 600 if (forward_signals) { 601 restore_signal_handlers(); 602 } 603 } 604 605 err_fork: 606 if (forward_signals) { 607 unblock_signals(&oldset); 608 } 609 err_ptty: 610 close(parent_ptty); 611 err_open: 612 pthread_mutex_unlock(&fd_mutex); 613 err_lock: 614 return rc; 615 } 616
08-20
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值