創建此程式以每 5 秒記錄一次計數器。當守護行程在后臺運行并記錄計數器時,需要運行 while 回圈。
我收到的錯誤是:分段錯誤(核心轉儲)。終端要求輸入一個數字,當我輸入數字時,我收到錯誤。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char* argv[])
{
int clos =0;
int count=0;
我認為下面的while回圈可能在錯誤的地方。
while(clos !=1){
printf("Type: ");
scanf("%d",clos);
if (clos !=1){
count = clos;
}
}
FILE *fp= NULL;
pid_t process_id = 0;
pid_t sid = 0;
// Create child process
process_id = fork();
// Indication of fork() failure
if (process_id < 0)
{
printf("fork failed!\n");
// Return failure in exit status
exit(1);
}
// PARENT PROCESS. Need to kill it.
if (process_id > 0)
{
printf("process_id of child process %d \n", process_id);
// return success in exit status
exit(0);
}
//unmask the file mode
umask(0);
//set new session
sid = setsid();
if(sid < 0)
{
// Return failure
exit(1);
}
// Change the current working directory to root.
chdir(".");
// Close stdin. stdout and stderr
// Open a log file in write mode.
fp = fopen ("Log.txt", "w ");
while (1)
{
//Dont block context switches, let the process sleep for some time
sleep(1);
fprintf(fp, "Logging info...\n");
fprintf(fp, counter);
fflush(fp);
// Implement and call some function that does core work for this daemon.
}
fclose(fp);
return (0);
}
uj5u.com熱心網友回復:
就像 kjohri 說的,你需要在 scanf 函式中傳遞一個指向 clos 的指標
添加 & 符號
scanf("%d", &clos);
^
此外,看起來您將變數命名為 count,但在您撰寫 counter 的函式中。而是寫:
fprintf(fp, "%d", count);
uj5u.com熱心網友回復:
必須寫fprintf的方式是給它加上一個計數器格式,所以它基本上和printf一樣
fprintf(fp,"%d",counter);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/406072.html
標籤:
