簡體   English   中英

簡單的C app給出了分段錯誤

[英]Simple C app gives segmentation fault

C從未成為我的強大力量,但我決定試一試。 以下是我的代碼,但在運行時,它會產生分段錯誤(核心轉儲)。

基本上我想要的是檢查文件夾是否為空(mtp設備安裝在其中),如果它是空的,則運行mount命令,如果沒有,則運行other命令。

#include <sys/types.h>
#include <dirent.h>
#include <libgen.h>
#include <libnotify/notify.h>
#include <stdio.h>
#include <unistd.h>

void main ()
{
  int n = 0;
  struct dirent *d;
  const char *dir_path="~/Nexus";
  DIR *dir = opendir(dir_path);
      while ((d = readdir(dir)) != NULL) {
        if(++n > 2)
          break;
      }
      closedir(dir);
      if (n <= 2) //Directory Empty
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * Mount = notify_notification_new ("Galaxy Nexus", "Mounted at ~/Nexus", "/home/tristan202/bin/test/android_on.png");
    system("jmtpfs ~/Nexus");
    notify_notification_show (Mount, NULL);
    }
      else
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * uMount = notify_notification_new ("Galaxy Nexus", "Unmounted", "/home/tristan202/bin/test/android_off.png");
    system("fusermount -u ~/Nexus");
    notify_notification_show (uMount, NULL);
    }
    }

歡迎任何建議。

編輯

#include <sys/types.h>
#include <dirent.h>
#include <libgen.h>
#include <libnotify/notify.h>
#include <stdio.h>
#include <unistd.h>

int main ()
{
  int n = 0;
  struct dirent *d;
  const char *dir_path="/home/tristan202/Nexus";
  DIR *dir = opendir(dir_path);
      while ((d = readdir(dir)) != NULL) {
        if(++n > 2)
          break;
      }
      closedir(dir);
      if (n <= 2) //Directory Empty
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * Mount = notify_notification_new ("Galaxy Nexus", "Mounted at ~/Nexus", "/home/tristan202/bin/test/android_on.png");
    system("jmtpfs ~/Nexus");
    notify_notification_show (Mount, NULL);
    }
      else
    {
    notify_init ("Galaxy Nexus mounter");
    NotifyNotification * uMount = notify_notification_new ("Galaxy Nexus", "Unmounted", "/home/tristan202/bin/test/android_off.png");
    system("fusermount -u ~/Nexus");
    notify_notification_show (uMount, NULL);
    }
    }

你有幾個問題:

  1. 您不檢查錯誤。 如果opendir(2)無法打開目錄並返回NULL ,則繼續運行,並將NULL傳遞給readdir(2)可能會導致段錯誤。 這可能是失敗的,因為......
  2. 當你寫"~" ,文件系統不明白你的意思,如"~/Nexus" 它試圖打開一個字面上的文件名為"~/Nexus" ~字符在文件系統中沒有特殊含義 - 它對shell有意義。 shell是執行波浪擴展的shell。 為了獲得所需的文件,您需要使用正確的完整絕對路徑或正確的相對路徑; 您可以使用getenv("HOME")在運行時查找自己的主目錄。 注意,在調用system(3)函數時可以使用~ ,因為system調用shell。
  3. main()未正確聲明。 它必須返回int ,而不是void

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM