码迷,mamicode.com
首页 > 其他好文 > 详细

第一章 Unix基础知识

时间:2015-03-29 15:00:13      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

 unix环境高级编程,尤晋元,2000年

只是把书里的代码敲一遍跑一下,熟悉一下书里的东西,没什么特别的;

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// list directory content
int ls(int, char**);

// copy input to output
int IO_Nobuffer();

int standardio();

int shell(int, char**);

int main(int argc, char** argv)
{
    printf("current process id: %d, user id: %d, group id: %d\n", 
                    getpid(), getuid(), getgid());    
    shell(argc, argv);
    //standardio();
    //IO_Nobuffer();
    //ls(argc, argv);
    exit(0);
}


#include <sys/types.h>
#include <dirent.h>

int ls(int argc, char** argv)
{
    if(argc < 2)
    {
        printf("a single argument is required!\n");
        exit(-1);
    }

    DIR* dp;
    struct dirent* dirp;

    dp = opendir(argv[1]);
    if(!dp)
    {
        printf("open %s failed!\n", argv[1]);
        exit(-1);
    }

    while((dirp = readdir(dp)) != NULL)
    {
        printf("%s\n", dirp->d_name);
    }

    closedir(dp);
    return 0;
}

#include <unistd.h>

#define BUFFER_SIZE 8192

int IO_Nobuffer()
{
    int n;
    char buffer[BUFFER_SIZE];

    while((n = read(STDIN_FILENO, buffer, BUFFER_SIZE)) > 0)
    {
        if(write(STDOUT_FILENO, buffer, n) != n)
        {
            printf("write error!\n");
            exit(-1);
        }
    }

    if(n < 0)
    {
        printf("read error!\n");
        exit(-1);
    }
    return 0;
}

int standardio()
{
    int c;
    while((c = getc(stdin))!= EOF)
    {
        printf("%d\n", c);
        if(putc(c, stdout) == EOF)
        {
            printf("output error!\n");
            exit(-1);
        }
    }

    if(ferror(stdin))
    {
        printf("input error!\n");
        exit(-1);
    }
    exit(0);
}

#include <sys/wait.h>
#include <string.h>
int shell(int argc, char** argv)
{
    char buffer[BUFFER_SIZE];
    pid_t pid;
    int status;

    printf("%% ");
    while(fgets(buffer, BUFFER_SIZE, stdin) != NULL)
    {
        buffer[strlen(buffer) - 1] = 0;

        if((pid = fork()) < 0)
        {
            printf("fork error!\n");
            exit(-1);
        }
        else if(pid == 0) // child process
        {
            execlp(buffer, buffer, (char*)0);
            exit(127);
        }

        if((pid = waitpid(pid, &status, 0)) < 0)
        {
            printf("wait error!\n");
            exit(-1);
        }
        
        printf("%% ");
    }

    return 0;
}

 

 

 

reference

unix环境高级编程<尤晋元>

http://en.wikipedia.org/wiki/Fork_(system_call)

http://unixhelp.ed.ac.uk/CGI/man-cgi?execve+2

http://unixhelp.ed.ac.uk/CGI/man-cgi?execlp+3

http://www.cplusplus.com/reference/cstdio/fgets/

 

第一章 Unix基础知识

标签:

原文地址:http://www.cnblogs.com/zstang/p/4375590.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!