LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: scutango

我的作业有誰能帮忙!

[复制链接]
发表于 2004-5-24 21:49:49 | 显示全部楼层

re

我那完整的找不到了,给你片段救救急,这个星期六若实在找不到,我就写个完整的,这是当年模仿shell的部分C程序,写得不好!如没有判断文件是否存在等等。
1 修改文件权限
[php]
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc,char *argv[])
{
     if(argc<2)
     {
          printf("请指定文件名\n");
          exit(255);
     }
     else
     {
          chmod(argv[1],S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
     }
     return 0;
}
[/php]

2 切换目录
[php]
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
    int fd;
    fd = opendir(argv[1]);
    if(fd<0)
    {
        printf("切换目录失败\n");
        exit(255);
    }
    else
    {
        fchdir(fd);
        close(fd);
    }
    return 0;
}
[/php]
3 当前目录
[php]
#include <unistd.h>
int main()
{
    char *ptr;
    ptr = get_current_dir_name();
    printf("当前目录是:%s\n",ptr);
    return 0;
}
[/php]

4 文件连接
[php]
#include <unistd.h>
int main(int argc ,char *argv[])
{
    int fd;
    if(argc<3)
    {
        printf("请指定文件名或连接名\n");
        exit(255);
    }
    else
    {
        fd = link(argv[1],argv[2]);
        if(fd<0)
        {
              printf("连接失败\n");
              exit(255);
        }
        else
        {
              printf("连接成功\n");
        }
    }
    return 0;
}
[/php]

5 遍历目录
[php]
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
int main()
{
    DIR *dir;
    struct dirent *ptr;
    int i;
    dir = opendir("/etc");
    while((ptr = readdir(dir)) != NULL)
    {
        printf("name:%s\n",ptr->d_name);
    }
    closedir(dir);
    return 0;
}
[/php]

就这些,自己可以先结合起来看看行不?switch()就可以了,欢迎指教
发表于 2004-5-24 22:42:27 | 显示全部楼层
拿来做练习不错啊
 楼主| 发表于 2004-5-31 10:37:12 | 显示全部楼层
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>

#define SHELL_NAME "sh1"
#define PROMPT_ENVIRONMENT_VARIABLE "ROMPT"

char *prompt;

int main(int argc, char **argv)  
{
char cmd[80];
int statval;
   
/* Determine prompt value. */
if ((prompt = getenv(PROMPT_ENVIRONMENT_VARIABLE)) == NULL)
prompt = SHELL_NAME ":";

/* Process commands until exit, or death by signal. */
while (1)  
{
/* Prompt and read a command. */
printf(prompt);
gets(cmd);

/* Process built-in commands. */
if(strcasecmp(cmd, "exit") == 0)
break;

/* Process non-built-in commands. */
if(fork() == 0) {
execlp(cmd, cmd, NULL);
fprintf(stderr, "%s: Exec %s failed: %s\n", argv[0],  
cmd, strerror(errno));
exit(1);
}  

wait(&statval);
if(WIFEXITED(statval))  
{
if(WEXITSTATUS(statval))
{
fprintf(stderr,
"%s: child exited with status %d.\n",
argv[0], WEXITSTATUS(statval));
}
} else {
fprintf(stderr, "%s: child died unexpectedly.\n",  
argv[0]);
}
}
}
发表于 2004-6-2 23:53:08 | 显示全部楼层
不麻烦吧。你找一本清华的操作系统实验书,尽管上面有很多错误,但改改都是没问题的。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表