📄 -
字号:
//实现管道双向传送的例子
#include <STDIO.H>
#include <UNISTD.H>
#include <DIRENT.H>
#include <LIMITS.H>
#define bufflen 1024
void server(), client();
typedef int pid_t;
int main(int argc, char **grav)
{
int n, pipe1[2], pipe2[2];
pid_t childpid;
if (pipe(pipe1) < 0)
printf("pipe error\n");
if (pipe(pipe2) < 0)
printf("pipe error\n");
if ( (childpid = fork()) < 0)
exit(0);
if (childpid > 0) {
close(pipe1[0]);
close(pipe2[1]);
client(pipe2[0], pipe1[1]);
waitpid(childpid, NULL, 0);
exit(0);
}
else {
close(pipe1[1]);
close(pipe2[0]);
server(pipe1[0], pipe2[1]);
exit(0);
}
}
//-----------------------------------------------------------------------------
void server(int readfd, int writefd)
{
ssize_t n;
char buff[bufflen], *ptr;
struct dirent *dirp;
DIR *dp;
if ( ( n = read(readfd, buff, bufflen) ) == 0) /*read dirname form IPC channel*/
exit(0);
buff[n] = '\0'; /* null terminate */
ptr = buff + n;
if ((dp = opendir(buff)) == NULL)
snprintf(ptr, sizeof(buff) - n, ": not find.\n"); /* tell client error */
else {
while ( ( dirp = readdir(dp) ) != NULL) {
if (strcmp(dirp->d_name, ".") == 0 ||
strcmp(dirp->d_name, "..") == 0) /* ignore . and .. directory */
continue;
strcpy(ptr, dirp->d_name); /* copy the filename list to the pipe */
n = strlen(dirp->d_name);
ptr += n;
*ptr = ' ';
ptr++;
}
*ptr = '\0'; /* null terminate */
}
n = strlen(buff);
if ( ( write(writefd, buff, n) ) != n)
exit(0);
closedir(dp);
}
//-----------------------------------------------------------------------------
void client(int readfd, int writefd)
{
size_t len;
ssize_t n;
char buff[bufflen];
fgets(buff, bufflen, stdin); /* read pathname from the standard input */
len = strlen(buff);
/* 删除路径名结尾处的回车符 */
if (buff[len-1] == '\n')
len--;
if ( ( write(writefd, buff, len) ) != len)
exit(0);
/* 循环从管道中读,直到读到内容为止 */
while ( (n = read(readfd, buff, bufflen) ) > 0)
if ( ( write(STDOUT_FILENO, buff, n) ) != n)
exit(0);
printf("\n");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -