Return value about System("command")

本文详细解释了System函数的工作原理,包括如何通过fork、execve和waitpid实现命令执行,并探讨了Exit函数的行为特点及其对父进程的影响。还介绍了如何正确解读System函数返回值的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

System函数:

是由fork、execve和waitpid三个系统调用实现的。
例如执行:system("ls /tm") --返回值为256

所以如果execve出错,则直接调用_exit(256),所以变量ret的值等于256.
在system函数执行时,会启动一个子进程运行shell,然后通过将ls /tm作为参数传给shell,如果shell命令运行有错,就调用exit XXX作为system的返回值返回,而XXX是system函数的返回值,而不是shell运行ls /tm后的返回值。

 

Exit函数:
exit时,退出状态码只能是一个字节,超过部分被截取.
在父进程获取其状态时,把这个字节的数据放在了低地址第二个字节位置了.这些都是对补码操作的.

因此,exit (-1) 和exit (255)时,父进程取的状态码是一样的,你无法区分

因此,我们一般只根据退出状态为0或则非0来判断成功或失败,而不做进一步的区分.

 

注意:

     如果把system的返回值除以256就可以得到真正的返回值了,因为system()返回的结果分两个部分,前面是命令的返回值,后面是运行因为信号终止时的信号值。所以要/256就是这个原因。

//-------------------------------------------------------------- // Press F1 to get help about using script. // To access an object that is not located in the current class, start the call with Globals. // When using events and timers be cautious not to generate memoryleaks, // please see the help for more information. //--------------------------------------------------------------- namespace Neo.ApplicationFramework.Generated { using System.Windows.Forms; using System; using System.Drawing; using Neo.ApplicationFramework.Tools; using Neo.ApplicationFramework.Common.Graphics.Logic; using Neo.ApplicationFramework.Controls; using Neo.ApplicationFramework.Interfaces; using System.Data; using System.IO; using System.Diagnostics; using System.Reflection; using System.Net; using System.Text; using System.Collections; using System.Collections.Generic; using System.Data.SQLite; public partial class SQLiteDatabaseBasic { System.Threading.Thread _Thread; const string m_pathUSB = @"\Hard Disk\"; public SQLiteConnection m_SqliteConnection; private DataTable dt = new DataTable(); private DataTable dt_export=new DataTable(); // 一頁要顯示幾筆資料 (預設十筆) private int m_PageSize = 38; private int m_CurrentPageIndex = 1; private int m_TotalPage = 0; private int m_firstid=0; // //dxl private int m_TotalCount; public int PageSize { set{ m_PageSize = value;} } public int TotalCount { get{ return m_TotalCount;} set{ m_TotalCount = value;} } public int TotalPages { get{ return m_TotalPage;} } public int CurrentPageIndex { get{ return m_CurrentPageIndex;} set{ m_CurrentPageIndex = value;} } private void CalculateTotalPages(DataTable dt) { m_TotalCount= dt.Rows.Count; int rowCount = dt.Rows.Count; if(rowCount>0) { m_firstid=Convert.ToInt32( dt.Rows[rowCount-1][0]); } else { m_firstid=0; } m_TotalPage = rowCount / m_PageSize; if (rowCount % m_PageSize > 0) m_TotalPage += 1; } public string BuildSqlGetCurrentTableString(string tableName, int Fisrtitem, int Lastitem) { string tmpResult = string.Format("SELECT * FROM {0} WHERE ", tableName); tmpResult += string.Format("ID <= {0} AND ", Fisrtitem.ToString()); tmpResult += string.Format("ID >= {0} ORDER BY Time DESC", Lastitem.ToString()); return tmpResult; } public DataTable GetCurrentGPSDataTable(string tableName) { int m_Fisrtitem = 0; int m_Lastitem = 0; try { m_Fisrtitem = m_TotalCount - (m_PageSize * (m_CurrentPageIndex - 1)); if(m_Fisrtitem < m_PageSize) { m_Lastitem = 1; } else { m_Lastitem = m_Fisrtitem - m_PageSize + 1; } string buildstring = BuildSqlGetCurrentTableString(tableName, m_Fisrtitem+m_firstid, m_Lastitem+m_firstid); return Select(buildstring); } catch (Exception) { return null; } } public void Export(DataTable dtable) { if(dtable!=null) { dt_export=dtable.Copy(); _Thread = new System.Threading.Thread(new System.Threading.ThreadStart(MainThread)); _Thread.Priority = System.Threading.ThreadPriority.Normal; _Thread.IsBackground = true; _Thread.Start(); } } void MainThread() { if(!Directory.Exists(m_pathUSB)) //报错:未找到USB设备 { //MessageBox.Show("Not found USB Disk"); Globals.NoUSB.Show(); Globals.Tags.ExportButtonColor.Value = 0; return; } int ProgressBar=0; ExportData(dt_export,"",m_pathUSB,ref ProgressBar); //dxl 启动闪烁 Globals.Tags.Dxl_number.Value = 0; Globals.Tags.ExportButtonColor.Value = 1; } ///删除指定数据表的null public void DelectNull(string TableName,string ListName) { try // in case of problems { // Create SQL query, ask database, fetch data and fill data set string sqlString = string.Format("DELETE FROM {0} WHERE {1} is NULL",TableName,ListName); ConnectDataBase(sqlString); } catch (SQLiteException) { } } public void ConnectDataBase(string CMDstr) { if(ConnectToDataBase()) { try { SQLiteCommand command = new SQLiteCommand(CMDstr, m_SqliteConnection); command.ExecuteNonQuery(); } catch{} } DisconnectFromDataBase(); } public DataTable Select(string Commandstring) { if (ConnectToDataBase()) { try { SQLiteDataAdapter da = new SQLiteDataAdapter(Commandstring, m_SqliteConnection); dt.Rows.Clear(); dt.Columns.Clear(); da.Fill(dt); da.Dispose(); } catch (Exception ex) { DisconnectFromDataBase(); // MessageBox.Show(ex.Message); return null; } } DisconnectFromDataBase(); return dt; } public DataTable SelectDataLog(string tablename,string starttime,string endtime) { if (ConnectToDataBase()) { try { string Commandstring=string.Format("SELECT * FROM {2} where Time > '{0}' and Time < '{1}' ORDER BY Time DESC ",starttime,endtime,tablename); SQLiteDataAdapter da = new SQLiteDataAdapter(Commandstring, m_SqliteConnection); dt.Rows.Clear(); dt.Columns.Clear(); da.Fill(dt); CalculateTotalPages(dt); da.Dispose(); } catch (Exception ex) { DisconnectFromDataBase(); // MessageBox.Show(ex.Message); return null; } } DisconnectFromDataBase(); return dt; } public DataTable SelectDataLog(string tablename) { if (ConnectToDataBase()) { try { string Commandstring=string.Format("SELECT * FROM {0} ORDER BY Time DESC ",tablename); SQLiteDataAdapter da = new SQLiteDataAdapter(Commandstring, m_SqliteConnection); dt.Rows.Clear(); dt.Columns.Clear(); da.Fill(dt); CalculateTotalPages(dt); da.Dispose(); } catch (Exception ex) { DisconnectFromDataBase(); // MessageBox.Show(ex.Message); return null; } } DisconnectFromDataBase(); return dt; } /// <summary> /// 导出指定的数据表数据到指定文件中 /// </summary> /// <param name="DataTable">需要导出数据的数据表</param> /// <param name="CSVName">导出文件名称</param> /// <param name="ExportPath">导出路径</param> /// <param name="ProgressBar">导出进度显示</param> /// <returns></returns> public void ExportData(DataTable DataTable,string CSVName,string ExportPath,ref int ProgressBar) { try { if(ExportPath==string.Empty) { ExportPath = @"c:\project\"; } if(CSVName==string.Empty) { CSVName=DateTime.Now.ToString("yyyy-M-d HH.m.s")+DataTable.TableName.ToString(); //CSVName=DataTable.TableName.ToString(); } if (!Directory.Exists(ExportPath)) { //Directory.CreateDirectory(ExportPath); return; } //string FilePath = ExcecutingPath + @"project files\" + FileName.ToString() + ".csv"; //string FilePath = @"c:\" + FileName.ToString() + ".csv"; string FilePath =ExportPath+" "+CSVName.ToString()+".csv"; FileStream Fx = new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.Write); StreamWriter writer = new StreamWriter(Fx, System.Text.Encoding.UTF8); //**********写表头内容,根据数据记录器项目重新填写******// string DataName=""; foreach (DataColumn column in DataTable.Columns) { DataName=DataName+column.ColumnName +","; } writer.WriteLine(DataName);//写数据表头 for (int i = 0; i < DataTable.Rows.Count; i++) { string writeLine = ""; for (int j = 0; j < DataTable.Columns.Count; j++) { writeLine += DataTable.Rows[i][j].ToString()+","; } if(writeLine!="") { writer.WriteLine(writeLine); //写数据到CSV文件 } ProgressBar=Convert.ToInt32(i*100/DataTable.Rows.Count); System.Threading. Thread.Sleep(100); } writer.Close(); Fx.Close(); ProgressBar=100; } catch(Exception ex) { // MessageBox.Show(ex.ToString()); } } private bool ConnectToDataBase() { if (m_SqliteConnection != null && m_SqliteConnection.State == ConnectionState.Open) return true; m_SqliteConnection = new SQLiteConnection(); m_SqliteConnection.ConnectionString = string.Format("data source={0}", Path.Combine(ExcecutingPath, "Database.db")); try { m_SqliteConnection.Open(); } catch (SQLiteException) { DisconnectFromDataBase(); return false; } return m_SqliteConnection.State == ConnectionState.Open; } private void DisconnectFromDataBase() { if (m_SqliteConnection != null) { if(m_SqliteConnection.State == ConnectionState.Open) { m_SqliteConnection.Close(); } m_SqliteConnection.Dispose(); m_SqliteConnection = null; } } private string ExcecutingPath { get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName); } } } }
最新发布
05-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值