【发布时间】:2013-12-02 02:02:16
【问题描述】:
我正在尝试完成作业代码。任务是创建一个程序,计算代码并行运行的文件夹中每个文本文件的行数。所以这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include "error.c"
char *getFileNameExtension(char *);
int isTxtFile(struct dirent *);
int countLines(struct dirent *);
int main(int argc , char *argv[]){
//Current Directory
DIR *currentDir;
//Current File
struct dirent *currDirFile;
pid_t pid;
int counter = 0;
/*
Struct stat "buf" variable , we'll need it
to check the selected file's st_mode(file type)
*/
struct stat buf;
int *lines = malloc(sizeof(int));
//Opens the directory where the executable exists with the dot(.)
currentDir = opendir(".");
if (currentDir){
/*In the while loop we read each file
of the current directory until we get a Nullable value */
while( ( currDirFile = readdir(currentDir) ) != NULL ){
if ( isTxtFile(currDirFile) == 1 ){
if ((pid=fork())<0){
err_sys("fork error");
}
//Child
else if(pid == 0){
exit(0);
}
//Father
else{
lines = realloc( lines , sizeof(int)*(counter+1) );
lines[counter] = countLines(currDirFile);
++counter;
}
}
if (pid==0){
printf("Child , pid = %d\n",pid);
}
else printf ("Father , pid = %d\n",pid);
}//End while
//close(currentDir);
}
int i ;
for(i=0;i<counter;++i){
printf("%d\n",lines[i]);
}
exit(1);
}
char *getFileNameExtension(char *filename){
//Gets the memory location of the last dot(.)
char *ext = strrchr(filename, '.');
return ext;
}
int isTxtFile(struct dirent *currDirFile){
struct stat buf;
/*With the lstat function we try to pass
the current file into the buf variable*/
if (lstat(currDirFile->d_name,&buf)<0){
printf("lstat error");
return 0;
}
/*If the st_mode(type) of the current file is regular
we print the name of the file*/
if (S_ISREG(buf.st_mode)){
char *c = getFileNameExtension(currDirFile->d_name);
if (c!=NULL){
//Check only for .txt files
if (strcmp(c,".txt")==0){
return 1;
}
else{
return 0;
}//End strcmp
}//End c!=NULL
}
else{
return 0;
}//END S_ISREG
}
int countLines(struct dirent *currentFile){
int fd = open(currentFile->d_name,O_RDONLY);
int n;
int lines = 0;
char buf;
while ((n=read(fd,&buf,1))>0){
if (buf=='\n') ++lines;
}
return (lines);
}
我以这种方式使用了 fork 函数,但我不确定它是否正确,因为当我运行它时,有 4 个父进程正在运行(如我所料),但还有 3 个子进程正在运行。谁能帮助我?实际上,我正在尝试为每个文本文件创建一个进程。
【问题讨论】:
标签: c unix parallel-processing synchronization fork