【发布时间】:2021-09-25 04:51:59
【问题描述】:
我从文件input1.txt 和input2.txt 在shell 脚本的帮助下输入到程序中,我希望在文件a.txt 和b.txt 中包含这些文件的内容,但在一个文件中可以,但在另一个文件中像这样的垃圾-489663824 -489663824 -489663824 -489663824 -489663824,谁知道这是怎么回事?
C 代码:
#include <stdio.h>
#include <stdlib.h>
// for multiprocessing
#include <unistd.h>
#include <sys/wait.h>
// for shared mutex
#include <pthread.h>
#include <sys/mman.h>
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
void write_to_file(const char *filename, const int n)
{
FILE *file = fopen(filename, "w");
int value;
printf("fill file with %d values: ", n);
for (int i = 0; i < n; ++i) {
scanf("%d", &value);
fprintf(file, "%d ", value);
}
fprintf(file, "\n");
printf("\n");
fclose(file);
}
void task(const char *filename, pthread_mutex_t *shared_mutex)
{
pthread_mutex_lock(shared_mutex);
write_to_file(filename, 5);
pthread_mutex_unlock(shared_mutex);
}
int main()
{
// mutex routine
pthread_mutex_t *shared_mutex;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED);
shared_mutex = (pthread_mutex_t *)mmap(NULL, sizeof(mutex), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
pthread_mutex_init(shared_mutex, &mutexattr);
// mutex routine
int pid = fork();
if (pid == -1) {
perror("fork() failed\n");
exit(1);
}
if (pid == 0) {
task("b.txt", shared_mutex);
return 0;
} else {
task("a.txt", shared_mutex);
wait(NULL);
}
// mutex routine
pthread_mutexattr_destroy(&mutexattr);
pthread_mutex_destroy(&mutex);
munmap(shared_mutex, sizeof(mutex));
// mutex routine
return 0;
}
shell脚本:
echo "9 8 7 6 5 " >> input1.txt
echo "4 3 2 1 0 " >> input2.txt
cat "input1.txt" "input2.txt" | ./test
cmp_files()
{
if cmp --silent -- "$1" "$2";
then
echo "write_to_file: ok"
else
echo "write_to_file: not ok"
fi
}
cmp_files "input1.txt" "a.txt"
cmp_files "input2.txt" "b.txt"
rm input1.txt
rm input2.txt
【问题讨论】:
-
好像
scanf失败了。可能所有文件数据都进入了另一个进程的缓冲区。 -
@user253751 我试过刷新它,但没有帮助
标签: c linux shell multiprocessing