第1关 socket之本地通信
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
int localsocket_test(const char *buffer, char *recv_buff, int length)
{
/*********begin***********/
static struct sockaddr_un srv_addr;
// creat unix socket
int connect_fd = socket(PF_UNIX,SOCK_STREAM,0);
if(connect_fd < 0)
{
perror("cannot creat socket");
return -1;
}
srv_addr.sun_family = AF_UNIX;
strncpy(srv_addr.sun_path, "./socket_test", strlen("./socket_test"));
//connect server
int ret = connect(connect_fd,(struct sockaddr*)&srv_addr,sizeof(srv_addr));
if (ret < 0)
{
perror("cannot connect server");
close(connect_fd);
return -1;
}
/*send message to server*/
if(0 > write(connect_fd, buffer, strlen(buffer)))
{
perror("send message failed\n");
close(connect_fd);
return -1;
}
if(0 < read(connect_fd, recv_buff, length))
{
ret = 0;
}
else
{
ret = -1;
}
close(connect_fd);
return ret;
/**********end************/
}
第2关 命名管理
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <limits.h>
#include <string.h>
void namepipe_commu(const char *buffer)
{
/***********begin***********/
int res = 0;
if (access("./my_fifo", F_OK) == -1) {
res = mkfifo("./my_fifo", 0777);
if (res == -1) {
perror("Error creating named pipe");
return;
}
}
int pipe_fd = open("./my_fifo", O_WRONLY);
if (pipe_fd == -1) {
perror("Error opening named pipe");
return;
}
ssize_t bytes_write = write(pipe_fd, buffer, strlen(buffer));
if (bytes_write == -1) {
perror("Error writing to named pipe");
}
close(pipe_fd);
/***********end***********/
}
第3关 消息队列
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct msgbuf
{
long mytype;
char bookname[100];
};
void mq_commu (void)
{
/*********Begin*********/
key_t key=0x1234;
//创建消息队列
int msgid=msgget(key,IPC_CREAT|0666);
struct msgbuf message;
message.mytype=66;
//发送三条消息
strcpy(message.bookname,"C");
msgsnd(msgid,&message,sizeof(struct msgbuf)-sizeof(long),0);
sleep(1);//等待一秒
strcpy(message.bookname,"Linux");
msgsnd(msgid,&message,sizeof(struct msgbuf)-sizeof(long),0);
sleep(1);//等待一秒
strcpy(message.bookname,"Makefile");
msgsnd(msgid, &message,sizeof(struct msgbuf)-sizeof(long),0);
sleep(1);//等待一秒
//最后发送一条"End"消息
strcpy(message.bookname,"End");
msgsnd(msgid,&message,sizeof(struct msgbuf)-sizeof(long),0);
/**********End**********/
}