1.打印进程ID
#include <stdio.h>
#include <stdlib.h>
int main(void) {
// 获取程序进程号
printf("hello world from process ID %d\n", getpid());
exit(0);
}
2.列出一个目录中所有文件的名字,ls命令的简要实现。
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main (int argc, char *argv[])
{
DIR *dp;
struct dirent *dirp;
printf("argc = %d \n", argc);
printf("argv[0] = %s \n", argv[0]);
if (argc != 2)
{
printf("usage: ls directory_name \n");
exit(0);
}
printf("argv[1] = %s\n", argv[1]);
if ((dp = opendir(argv[1])) == NULL)
{
printf("can't open %s", argv[1]);
exit(0);
}
while ((dirp = readdir(dp)) != NULL)
{
printf("%s\n", dirp->d_name);
}
closedir(dp);
return 0;
}
3.从标准输入读,并向标准输出写(可用于复制任一普通文件)
apue.h
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
ioTest.h
#include "apue.h"
#define BUFFSIZE 4096
void main()
{
int n;
char buf[BUFFSIZE];
while( (n = read(STDIN_FILENO, buf, BUFFSIZE)) > 0)
{
if (write(STDOUT_FILENO, buf, n) != n)
{
printf("write error");
exit(1);
}
}
if (n < 0)
{
printf("read error");
exit(1);
}
exit(0);
}
编译$ gcc -o ioTest ioTest.c
执行$./ioTest > data.txt 标准输入是终端,标准输出则重定向到文件data.txt。如果此输出文件并不存在,则shell会创建它。
执行$./ioTest < infile > outfile 会将名为infile文件的内容复制到outfile。