写一个popen函数和索引顺序存取文件

mybluedog24 2011-03-25 05:29:31
用基本的unix/c的函数写一个popen函数
用基本的unix/c的函数写一个索引顺序存取文件

原题:
-Use primitive Unix/C process functions (pipe, fork, exec, ...) to implement a popen.
-Use primitive Unix/C file IO functions (open, stat, read, write, lseek) to implement an indexed sequential access file.
...全文
107 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
mybluedog24 2011-03-29
  • 打赏
  • 举报
回复
算了~谢谢各位
hukui161 2011-03-26
  • 打赏
  • 举报
回复
popen源码
/*
* popen.c Written by W. Richard Stevens
*/

#include <sys/wait.h>
#include <errno.h>
#include <fcntl.h>
#include "ourhdr.h"

static pid_t *childpid = NULL;
/* ptr to array allocated at run-time */
static int maxfd; /* from our open_max(), {Prog openmax} */

#define SHELL "/bin/sh"

FILE *
popen(const char *cmdstring, const char *type)
{
int i, pfd[2];
pid_t pid;
FILE *fp;

/* only allow "r" or "w" */
if ((type[0] != 'r' && type[0] != 'w') || type[1] != 0) {
errno = EINVAL; /* required by POSIX.2 */
return(NULL);
}

if (childpid == NULL) { /* first time through */
/* allocate zeroed out array for child pids */
maxfd = open_max();
if ( (childpid = calloc(maxfd, sizeof(pid_t))) == NULL)
return(NULL);
}

if (pipe(pfd) < 0)
return(NULL); /* errno set by pipe() */

if ( (pid = fork()) < 0)
return(NULL); /* errno set by fork() */
else if (pid == 0) { /* child */
if (*type == 'r') {
close(pfd[0]);
if (pfd[1] != STDOUT_FILENO) {
dup2(pfd[1], STDOUT_FILENO);
close(pfd[1]);
}
} else {
close(pfd[1]);
if (pfd[0] != STDIN_FILENO) {
dup2(pfd[0], STDIN_FILENO);
close(pfd[0]);
}
}
/* close all descriptors in childpid[] */
for (i = 0; i < maxfd; i++)
if (childpid[ i ] > 0)
close(i);

execl(SHELL, "sh", "-c", cmdstring, (char *) 0);
_exit(127);
}
/* parent */
if (*type == 'r') {
close(pfd[1]);
if ( (fp = fdopen(pfd[0], type)) == NULL)
return(NULL);
} else {
close(pfd[0]);
if ( (fp = fdopen(pfd[1], type)) == NULL)
return(NULL);
}
childpid[fileno(fp)] = pid; /* remember child pid for this fd */
return(fp);
}

int
pclose(FILE *fp)
{

int fd, stat;
pid_t pid;

if (childpid == NULL)
return(-1); /* popen() has never been called */

fd = fileno(fp);
if ( (pid = childpid[fd]) == 0)
return(-1); /* fp wasn't opened by popen() */

childpid[fd] = 0;
if (fclose(fp) == EOF)
return(-1);

while (waitpid(pid, &stat, 0) < 0)
if (errno != EINTR)
return(-1); /* error other than EINTR from waitpid() */

return(stat); /* return child's termination status */
}
justkk 2011-03-26
  • 打赏
  • 举报
回复
索引顺序存取文件
是怎么一个访问方式?
mybluedog24 2011-03-26
  • 打赏
  • 举报
回复
求助啊各位...
mybluedog24 2011-03-26
  • 打赏
  • 举报
回复
求求各位帮帮忙..真的不会写..
tangxianghenggood 2011-03-25
  • 打赏
  • 举报
回复
这个可以大力讨论一下

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧