话不多说,直接放源码 从unix网络编程中找出来修改的,注意不能使用printf函数
使用write( STDOUT_FILENO, buff,n); 代替printf
#include "stdio.h"
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
/**
* 信号处理的时候,不能使用printf函数
*
*
*
* */
extern int *__errno_location (void) __THROW __attribute_const__;
# define errno (*__errno_location ())
#define MAXLINE 4096
void client(int readfd, int writefd)
{
size_t len;
ssize_t n;
char buff[MAXLINE]="hello this is client";
write(writefd, buff,strlen(buff));
/* 4read from IPC, write to standard output */
while ( (n = read(readfd, buff, MAXLINE)) > 0)
{
}
}
void server(int readfd, int writefd)
{
int fd;
ssize_t n;
char buff[MAXLINE+1];
/* 4open succeeded: copy file to IPC channel */
while ( (n = read(readfd, buff, MAXLINE)) > 0)
{
write( STDOUT_FILENO, buff,n);
}
}
int main(int argc, char **argv)
{
int pipe1[2], pipe2[2];
pid_t childpid;
pipe(pipe1); /* create two pipes */
pipe(pipe2);
if ( (childpid = fork()) == 0) { /* child */
close(pipe1[1]);
close(pipe2[0]);
server(pipe1[0], pipe2[1]);
exit(0);
}
/* 4parent */
close(pipe1[0]);
close(pipe2[1]);
client(pipe2[0], pipe1[1]);
waitpid(childpid, NULL, 0); /* wait for child to terminate */
exit(0);
}
或者用这种方法socketpair
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAXLINE 255
void error_msg_quit(char *string, int line)
{
char msg[MAXLINE] = {0};
int len = 0;
sprintf(msg, "%s", string);
len = strlen(string);
snprintf(msg + len, strlen(strerror(errno)), ",line:%d,%s\n", line, strerror(errno));
fputs(msg, stdout);
exit(errno);
}
int main(int argc, char **argv)
{
int fd[2], n;
char ch;
pid_t child_pid;
//create pipe
//pipe(fd);
socketpair(AF_UNIX, SOCK_STREAM, 0, fd);//if donot set this option,it won't work properly.
if ((child_pid = fork()) == 0)
{
//child
sleep(3);
if ((n = read(fd[0], &ch, 1)) != 1)
{
error_msg_quit("read error", __LINE__);
}
printf("child read:%c\n", ch);
write(fd[0], "this is child", 5);
exit(0);
}
//parent
write(fd[1], "this is parent", 5);
if ((n = read(fd[1], &ch, 1)) != 1)
{
error_msg_quit("read error", __LINE__);
}
printf("parent read:%c\n", ch);
exit(0);
}
popen 用于执行命令的
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
//15.3 popen
FILE* fp = NULL;
char buf[100] = {0};
if((fp = popen("ls -la", "r")) == NULL) {
printf("popen error !\n");
exit(1);
}
//通过返回的文件指针读取文件内容
while(fgets(buf, 100, fp) != NULL) {
//每次读取一行,并打印
printf("%s", buf);
}
//这里注意记得关闭
pclose(fp);
exit(0);
}