我们来简要模拟一下linux中的ls命令, 代码如下:

#include <stdio.h>
#include <dirent.h> //  DIR,struct dirent,opendir, readdir

int main(int argc, char *argv[])  
{  
	printf("%d\n", getppid());

	DIR *dp;  // 指向目录
	struct dirent *dirp; // 指向目录中的对象
	
	if(argc != 2)  
	{  
		printf("error\n");  
		return 1;
	}  
	
	// 打开一个目录
	if((dp = opendir(argv[1])) == NULL)  
	{  
		printf("can`t open %s\n", argv[1]);  
		return 1;
	}  
	
	// 读取目录中的对象, 然后打印出其名字d_name
	while((dirp = readdir(dp)) != NULL)  
	{  
		printf("%s\n", dirp->d_name);  
	}  
	
	closedir(dp);  // 关闭目录
	
	return 0;
}  
     运行结果如下:

 [taoge@localhost learn_c]$ ls
test.c
[taoge@localhost learn_c]$ echo $$
2812
[taoge@localhost learn_c]$ gcc test.c 
[taoge@localhost learn_c]$ ./a.out /home/taoge/Desktop
2812
.
learn_c
..
[taoge@localhost learn_c]$ 


     顺便说一下, 当前shell是一个运行的进程, 它的pid是2812,  ./a.out对应的进程实际上是shell进程的子进程, 从上述结果也可以看得出来。  在上面的模拟中, 我们的a.out实际上就是系统的ls

  

    




本文转载:CSDN博客