用C语言编写程序建立一个pipe

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1、用C语言编写程序,建立一个pipe, 同时父进程生成一个子进程,子进程向pipe写入一

个字符串”Hello.”,父进程从pipe中读取该字符串。5'

#include

#include

#include

#include

#include

#include

int main()

{

char buf[20];

int piledes[2];

pid_t pid;

int ret;

if(ret = pipe(piledes) == -1)

{

perror("error on pipe:");

exit(-1);

}

else

{

pid = fork();

if(pid < 0)

{

perror("error on fork:");

exit(-1);

}

else if(pid == 0)

{

close(piledes[0]);

printf("to fu:");

fgets(buf,sizeof(buf)-1,stdin);

if((ret = write(piledes[1],buf,strlen(buf))) < 0)

{

perror("error on writing:");

exit(-1);

}

close(piledes[1]);

}

else

{

close(piledes[1]);

if((ret = read(piledes[0],buf,sizeof(buf)-1)) < 0)

{

perror("error on reading:");

exit(-1);

}

buf[ret] = '\0';

printf("from zi:%s\n",buf);

close(piledes[0]);

}

}

return 0;

}

2、编写一个 C语言程序lswc,使之功能能和ls | wc 等价。(也就是利用,fork,exec,以及ls,wc,以及重定向,或者是管道的系统调用) 13’

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

#include

int main(int argc,char *argv[])

{

int pildes[2];

int ret;

char *argument[3];

pid_t pid;

char buf[1000];

if(argc < 2)

{

printf("que shao can shu\n");

exit(0);

}

argument[0] = "ls";

argument[1] = "/";

argument[2] = NULL;

if((ret = pipe(pildes)) < 0)

{

perror("error on pipe:");

exit(-1);

}

pid = fork();

if(pid <0)

{

printf("fork error\n");

exit(-1);

}

if(pid == 0)

{

close(pildes[0]);

dup2(pildes[1],1);

execvp("ls",argument);

close(pildes[1]);

}

else

{

close(pildes[1]);

// dup2(fildes[0],0);

if(strcmp((argv[1]),"wc") == 0)

{

bzero(buf,sizeof(buf));

if((ret = read(pildes[0],buf,sizeof(buf))) < 0)

{

printf("error on reading:");

exit(-1);

}

buf[ret] = '\0';

printf("%s",buf);

close(pildes[0]);

}

}

return 0;

}

3、实现一个具有头节点的链表。要求具有create, insert, delete, search功能,能对链表。

编写一个应用程序,使用上面的函数。 10'

#include

#include

#include

#include

#define PASSWD 111111

struct student

{

int num;

char name[20];

float grade;

struct student *next;

};

typedef struct student stuNode;

typedef struct student *stuPtr;

int stuwrite(stuPtr head)

{

FILE *fp;

fp = fopen("stu","w");

while(head->next != NULL)

{

head = head->next;

fwrite(head,sizeof(stuNode),1,fp);

}

close(fp);

相关文档
最新文档