socketpair的用法和理解之非阻塞

该博客演示了在一个进程中如何使用socketpair创建两个套接字,并通过fcntl设置它们的阻塞与非阻塞模式。在阻塞模式下,read函数会等待数据可用,而write可能会阻塞直到数据被完全写出。通过fcntl调用,将套接字设置为非阻塞模式,使得read函数在无数据时不会阻塞,但write仍可能阻塞。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 阻塞状态:读阻塞

    #include <stdio.h> 
    #include <string.h> 
    #include <unistd.h> 
    #include <sys/types.h> 
    #include <error.h> 
    #include <errno.h> 
    #include <sys/socket.h> 
    #include <stdlib.h> 
    #include <fcntl.h> 
    #define BUF_SIZE 30 
     
    int main(){ 
            int s[2]; 
			int ss[2];
            int w,r; 
            char * string = "This is a test string"; 
            char * buf = (char*)calloc(1 , BUF_SIZE); 
     
            if( socketpair(AF_UNIX,SOCK_STREAM,0,s) == -1 ){ 
                    printf("create unnamed socket pair failed:%s\n",strerror(errno) ); 
                    exit(-1); 
            } 
			if( socketpair(AF_UNIX,SOCK_STREAM,0,ss) == -1 ){ 
				printf("create unnamed socket pair failed:%s\n",strerror(errno) ); 
				exit(-1); 
			} 
            /*******test in a single process ********/ 
		while(1){
			sleep(1);
           /* if( ( w = write(s[0] , string , strlen(string) ) ) == -1 ){ 
                    printf("Write socket error:%s\n",strerror(errno)); 
                    //exit(-1); 
            } 
            ****read*******/
			if( (r = read(s[1], buf , BUF_SIZE )) == -1){ 
				printf("Read from socket error:%s\n",strerror(errno) ); 
				//exit(-1); 
			} 
			printf("Read string in same process : %s \n",buf); 
			if( (r = read(s[0], buf , BUF_SIZE )) == -1){ 
				printf("Read from socket s0 error:%s\n",strerror(errno) ); 
				//exit(-1); 
			} 
			printf("Read from s0 :%s\n",buf);  
		}
            printf("Test successed\n"); 
            exit(0); 
    } 




int fla= fcntl(s[0], F_GETFL, 0); //获取文件的flags值。
fcntl(s[0], F_SETFL, fla | O_NONBLOCK); //设置成非阻塞模式;
int f=fcntl(s[1], F_GETFL, 0); //获取文件的flags值
fcntl(s[1], F_SETFL, f | O_NONBLOCK); //设置成非阻塞模式;

状态:read函数不会阻塞、write函数会阻塞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值