add2.c 编译后生成执行文件add2
一个简单的加法运算器 通过标准输入端获取参数 标准输出端返回结果
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXLINE 1024
int main(int argc,char *argv[])
{
int n,int1,int2;
char line[MAXLINE];
while((n = read(STDIN_FILENO,line,MAXLINE)) > 0)
{
line[n]=0;
if(sscanf(line, "%d%d", &int1, &int2) == 2)
{
sprintf(line,"%d\n",int1 + int2);
n = strlen(line);
if(write(STDOUT_FILENO,line,n) != n)
{
printf("write error\n");
exit(1);
}
}
else
{
if(write(STDOUT_FILENO,"invalid args\n",13) != 13)
{
printf("write error\n");
exit(1);
}
}
}
return 0;
}
add1.c 编译后生成执行文件add1
add1运行时将提示输入参数(123 456)获取参数后调用add2进行加法运算,获取结果并打印
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#define MAXLINE 1024
static void sig_pipe(int);
int main(int argc,char *argv[])
{
int n,fd1[2],fd2[2];
pid_t pid;
char line[MAXLINE];
if(signal(SIGPIPE,sig_pipe) == SIG_ERR)
{
printf("signal error\n");
exit(1);
}
if(pipe(fd1) < 0 || pipe(fd2) < 0)
{
printf("pipe error\n");
exit(1);
}
if((pid = fork()) < 0)
{
printf("fork error\n");
exit(1);
}
else if(pid > 0)
{
close(fd1[0]);
close(fd2[1]);
while(fgets(line,MAXLINE,stdin) != NULL)
{
n = strlen(line);
if(write(fd1[1],line,n) != n)
{
printf("write error to pipe\n");
exit(1);
}
if((n = read(fd2[0],line,MAXLINE)) < 0)
{
printf("read error from pipe\n");
exit(1);
}
if(n == 0)
{
printf("chile closed pipe\n");
break;
}
line[n]=0;
if(fputs(line,stdout) == EOF)
{
printf("fputs error\n");
break;
}
}
if(ferror(stdin))
{
printf("fgets error on stdin\n");
exit(1);
}
exit(0);
}
else
{
close(fd1[1]);
close(fd2[0]);
if(fd1[0] != STDIN_FILENO)
{
if(dup2(fd1[0],STDIN_FILENO) != STDIN_FILENO)
{
printf("DUP2 error to stdin\n");
exit(1);
}
close(fd1[0]);
}
if(fd2[1] != STDOUT_FILENO)
{
if(dup2(fd2[1],STDOUT_FILENO) != STDOUT_FILENO)
{
printf("DUP2 error to stdout\n");
exit(1);
}
close(fd2[1]);
}
if(execl("./add2","add2",(char *)0) < 0)
{
printf("execl error\n");
exit(1);
}
}
return 0;
}
static void sig_pipe(int signo)
{
printf("SIGPIPE caught\n");
exit(1);
}