我试图同时杀死多个进程。 我使用这个简单的for循环通过PID编号终止进程。
using System;
using System.Collections.Generic;
using System.Linq;
namespace ShowTest
{
public class Depot
{
public string Name { get; set; }
public Dictionary<Order, Dictionary<int, OrderLine>> Orders { get; set; } = new Dictionary<Order, Dictionary<int, OrderLine>>(new OrderEqualityComparer());
}
public class Order
{
public string Reference { get; set; }
public DateTime DepotDate { get; set; }
}
#region comparer
public class OrderEqualityComparer : IEqualityComparer<Order>
{
public bool Equals(Order x, Order y)
{
return (x.Reference == y.Reference);
}
public int GetHashCode(Order obj)
{
return (obj.Reference.GetHashCode());
}
}
#endregion
public class OrderLine
{
public int Qty { get; set; }
public string ExternalRef { get; set; }
}
public class Demo
{
public static void Main()
{
#region Setting up values
Order order = new Order { DepotDate = DateTime.Parse("15/01/2010"), Reference = "myOrderRef" };
OrderLine orderLine1 = new OrderLine { ExternalRef = "Foo", Qty = 4 };
OrderLine orderLine2 = new OrderLine { ExternalRef = "Bar", Qty = 8 };
var orderLines = new Dictionary<int, OrderLine>();
orderLines.Add(1, orderLine1);
orderLines.Add(2, orderLine2);
var orders = new Dictionary<Order, Dictionary<int, OrderLine>>();
orders.Add(order, orderLines);
Depot myDepot = new Depot { Name = "Funhouse", Orders = orders };
#endregion
foreach (string oRef in myDepot.Orders.Select(l => l.Key.Reference))
{
//for each order reference, there is an order containing many order lines. So, first we get the relevant order
var thisOrder = (from l in myDepot.Orders
where l.Key.Reference == oRef
select l.Value.Values) as Dictionary<int, OrderLine>;
if (thisOrder == null) { Console.WriteLine("Why is thisOrder null when the search criterion was retrieved from the order itself?"); }
else { Console.WriteLine("Hooray, the damnable thing has contents!"); }
}
}
}
}
如果我在终端中手动输入该循环,则该循环工作正常。
但是如果我想从文件for i in $(ps -ejH | grep omn_bdxtrc|awk '{print $1}'); do kill ${i}; done
中获取它,它将返回此输出。
(*.sh)
尝试了多种手动操作方式,但无法从文件中手动操作。
有任何想法为什么会这样?
先谢谢了。
答案 0 :(得分:3)
似乎PID是作为单个参数传递的,该参数由换行符分隔,kill
似乎并不受欢迎。
我将通过完全删除循环并将PID通过kill
传递到xargs
来简化方法:
ps -ejH | grep omn_bdxtrc | awk '{print $1}' | xargs kill
或者(如果您出于某些原因而没有或不想使用xargs
),则可以保留当前循环,并通过使用以下命令将所有可能的换行符更改为空格来清理awk的输出tr
:
for i in $(ps -ejH | grep omn_bdxtrc | awk '{print $1}' | tr '\n' ' '); do kill ${i}; done
但这并不那么优雅。
假设您知道进程的确切名称,也许最优雅的解决方案是使用killall
:
killall omn_bdxtrc
或者如果您不知道确切的名称并且需要匹配一部分名称:
killall --regexp '.*omn_bdxtrc.*'