[APUE]第一章UNIX基础知识总结
UNIX简介操作系统的狭义定义,是将操作系统定义为一种控制计算机资源,提供程序运行环境的软件,通常我们称之为内核,内核提供接口供上层应用调用,也叫做System Call(系统调用)。同时,为了方便应用程序使用内核,通常都会有公用函数库,应用程序既可以使用系统调用,也可以使用公用函数库。系统调用和公用函数库实际上并不是同一个东西,但是对于开发者来说,可以当作同一个层,都可以使用C函数来调用。再向上,就是shell终端,作为人机交互部分,最外层则是应用程序。 文件和目录#include "apue.h"
#include <dirent.h>
int
main(int argc,char *argv[])
{
DIR *dp;
struct dirent *dirp;
if (argc != 2)
err_quit("usage: ls directory_name");
if ((dp = opendir(argv[1])) == NULL)
err_sys("can't open %s",argv[1]);
while ((dirp = readdir(dp)) != NULL)
printf("%sn",dirp->d_name);
closedir(dp);
exit(0);
}
函数opendir()打开我们传入的目录,返回的是目录流,函数readdir()读取目录流信息,readdir()返回参数dir目录流的下个目录进入点。 输入输出#include "apue.h"
#define BUFFSIZE 4096
int
main(void)
{
int n;
char buf[BUFFSIZE];
while ((n = read(STDIN_FILENO,buf,BUFFSIZE)) > 0)
if (write(STDOUT_FILENO,n) != n)
err_sys("write error");
if (n < 0)
err_sys("read error");
exit(0);
}
这个例子让我看到时闹了个笑话: 若以下列方式执行该程序:
./a.out < infile >outfile
我当时在想<>是什么奇怪的语法,难道是可以省略文件infile的意思,直到我在心爱的mac上运行了这个程序。 #define STDIN_FILENO 0 /* standard input file descriptor */
#define STDOUT_FILENO 1 /* standard output file descriptor */
#define STDERR_FILENO 2 /* standard error file descriptor */
实际上0、1、2就默认已经被使用了,如果我们在此基础上新打开一个文件,实际上是增加在3的位置,而且每个进程都有0、1、2的文件描述符。 程序与进程程序是一段放置于磁盘上的二进制代码,内核使用exec函数族来讲进程读入内存,并且执行程序,在内存中运行的程序实例被称为进程,Unix标准要求每个进程都有唯一表示符(process ID即pid),pid是一个非负整数。 #include "apue.h"
int
main(void)
{
printf("hello world from process ID %ldn",(long)getpid());
exit(0);
}
getpid函数得到进程ID,getpid返回一个pid_t数据类型,虽然大多数进程ID可以用整数表示,但用长整型可以提高移植性。 #include "apue.h"
#include <sys/wait.h>
int
main(void)
{
char buf[MAXLINE]; /* from apue.h */
pid_t pid;
int status;
printf("%% "); /* print prompt (printf requires %% to print %) */
while (fgets(buf,MAXLINE,stdin) != NULL) {
if (buf[strlen(buf) - 1] == 'n')
buf[strlen(buf) - 1] = 0; /* replace newline with null */
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* child */
execlp(buf,(char *)0);
err_ret("couldn't execute: %s",buf);
exit(127);
}
/* parent */
if ((pid = waitpid(pid,&status,0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
在这个程序里使用了标准I/O函数fgets从标准输入读取一行,当输入文件结束符Ctrl+D时候,fgets返回一个null指针,然后就会直接执行exit(0);让进程退出 #include "apue.h"
#include <sys/wait.h>
static void sig_int(int); /* our signal-catching function */
int
main(void)
{
char buf[MAXLINE]; /* from apue.h */
pid_t pid;
int status;
if (signal(SIGINT,sig_int) == SIG_ERR)
err_sys("signal error");
printf("%% "); /* print prompt (printf requires %% to print %) */
while (fgets(buf,0)) < 0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
void
sig_int(int signo)
{
printf("interruptn%% ");
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |