您好,null
我在阅读时遇到字符问题,并尝试fseek()
在多进程程序中使用函数打印文件的字符。这是我的简单代码,
#include <stdio.h> /* basic I/O routines. */
#include <unistd.h> /* define fork(), etc. */
#include <sys/types.h> /* define pid_t, etc. */
#include <sys/wait.h> /* define wait(), etc. */
#include <signal.h> /* define signal(), etc. */
#include <pthread.h>
#include <time.h>
void print_screen(int i);
int counter=0;
int main(int argc, char* argv[]) {
FILE* fptr;
fptr = fopen("sample.txt","w");
int counter = atoi(argv[1]);
int i,k;
int temp;
pid_t child_pid;
int child_status;
char array[counter];
srand ( time(NULL) );
for(i=0; i<counter; i++){
temp = rand()%4;
if( temp==0 ) {
fprintf(fptr,"A\n");
array[i]='A';
}
else if( temp==1 ) {
fprintf(fptr,"C\n");
array[i]='C';
}
else if( temp==2 ) {
fprintf(fptr,"G\n");
array[i]='G';
}
else if( temp==3 ) {
fprintf(fptr,"T\n");
array[i]='T';
}
}
fclose(fptr);
for(i=1; i<=counter; i++){
child_pid = fork();
switch(child_pid) {
case -1:
printf("Error occured with fork()\n");
exit(1);
case 0:
print_screen(i); /* Child Process */
exit(0);
}
}
wait(&child_status);
execl("/usr/bin/killall","killall","tail",(char *) 0);
return 0;
}
void print_screen(int i){
char* str;
FILE* fptr;
fptr=fopen("sample.txt","r");
fseek(fptr,i,SEEK_SET);
fscanf(fptr,"%s",str);
printf("Process Number %d, Character = %s\n",i,str);
sleep(1);
fclose(fptr);
return;
}
假设我进入./sample 10
命令行,所以程序将在 sample.txt 中打印 10 个字符,然后将创建 10 个子进程,每个子进程都尝试选择一个字符并打印到屏幕上。此外,如您所见,我发送i
为设置偏移量的参数。但正如我提到的,它打印为空。这是该计划的前景。
Process Number 7, Character = (null)
Process Number 6, Character = (null)
Process Number 5, Character = (null)
Process Number 3, Character = (null)
Process Number 8, Character = (null)
Process Number 4, Character = (null)
Process Number 9, Character = (null)
Process Number 10, Character = (null)
Process Number 2, Character = (null)
Process Number 1, Character = (null)
txt文件是这样的。
G
A
A
T
G
C
C
A
A
T
如果您能提供帮助,我将不胜感激,无论如何,谢谢。
编辑:我意识到我编译就像$ gcc sample.c -o sample -lpthread
它打印出空值一样。另一方面,我编译它时没有-lpthread
打印字符但不正确,例如这是文本文件。
T
G
G
T
G
终端给出这样的输出。
Process Number 1, Character = G
Process Number 2, Character = G
Process Number 3, Character = G
Process Number 4, Character = G
Process Number 5, Character = T