[C++] 纯文本查看 复制代码
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
print_line(int n)
{
char buf[32];
const char *ptr = "hello";
snprintf(buf, sizeof(buf), "Line #%d\n", n);
write(1, buf, strlen(buf));
}
int main()
{
int fd;
print_line(1);
print_line(2);
print_line(3);
/*重定向标准输出 stdout 到文件 dup.out 中*/
fd = open("dup.out", O_WRONLY|O_CREAT,0666);
assert(fd>=0);
printf("fd=%d\n", fd);
dup2(fd, 1);
print_line(4);
print_line(5);
print_line(6);
close(fd);
close(1);
return 0;
}
[C++] 纯文本查看 复制代码
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char **argv, char **environ)
{
pid_t pid;
int fd[2];
if (pipe(fd)) {
printf("create pipe failed!\\n");
exit(1);
}
pid = fork();
switch(pid) {
case -1:
printf("fork error!\\n");
exit(1);
case 0:
close(fd[0]);
close(1);
dup(fd[1]);
sleep(5);
system("ls -l");
exit(0);
default:
close(fd[1]);
char message[4096];
read(fd[0], message, 4096);
printf("hello world\\n");
printf("%", message);
}
return 0;
}