5-06 1,091 views
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int result = -1;
int fd[2];
int nbytes;
pid_t pid;
char hello[] = "Hello World, my pipe";
char readBuffer[100];
int *read_fd = &fd[0];
int *write_fd = &fd[1];
memset(readBuffer, 0, sizeof(readBuffer));
result = pipe(fd);
if (-1 == result)
{
printf("fail to create pipe\n");
return -1;
}
pid = fork();
printf("pid = %d\n", pid);
if (-1 == pid)
{
printf("fail to work\n");
return -1;
}
if(0 == pid)
{
close(*read_fd);
result = write(*write_fd, hello, strlen(hello));
return 0;
}
else
{
close(*write_fd);
printf("sizeof(readBuffer) = %lu\n", sizeof(readBuffer));
nbytes = read(*read_fd, readBuffer, sizeof(readBuffer));
printf("the parent received %d bytes data: %s\n", nbytes, readBuffer);
}
return 0;
}
线程间通信
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
typedef struct _message{
int arg;
char* msg;
}message;
static int fd[2];
void mythread()
{
while(1){
message msg;
read(fd[0], &msg, sizeof(message));
printf("read message: %s, arg = %d\n", msg.msg, msg.arg);
}
}
int main(void)
{
int result;
pthread_t id1;
result = pipe(fd);
if(-1 == result){
printf("faild to create pipe");
}
int ret = pthread_create(&id1, NULL, (void*)mythread, NULL);
if(ret)
{
printf("create pthread error!\n");
return -1;
}
int i = 10;
while(1){
char* hello = "hello world";
message msg;
msg.arg = i++;
msg.msg = hello;
write(fd[1], &msg, sizeof(msg));
printf("write message and sleep ... \n");
sleep(1);
}
}
There is apparently a lot to realize about this. I suppose
you made certain good points in features also. http://www.51tooling.net/bbs/home.php?mod=space&uid=5476461&do=profile