Russian Qt Forum
Апрель 25, 2024, 09:22 *
Добро пожаловать, Гость. Пожалуйста, войдите или зарегистрируйтесь.
Вам не пришло письмо с кодом активации?

Войти
 
  Начало Форум WIKI (Вики)FAQ Помощь Поиск Войти Регистрация  
  Просмотр сообщений
Страниц: 1 [2] 3 4 ... 65
16  Qt / Работа с сетью / Re: Net-SNMP, mib2c(Решено) : Май 04, 2022, 15:38
 Улыбающийся

Я зря закомментировал все case  Строит глазки  кроме case MODE_SET_ACTION
из-за этого и выдавалась ошибка

Код
C++ (Qt)
 
/*
* Note: this file originally auto-generated by mib2c
* using mib2c.scalar.conf
*/

 
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include "collins_Avionics.h"
 
 
static u_char mydata = 10;
 
/** Initializes the collins_Avionics module */
void
init_collins_Avionics(void)
{
   const oid afdxSwitchEDACTestResult_oid[] = { 1,3,6,1,4,1,8419,11,1,1 };
 
 DEBUGMSGTL(("collins_Avionics", "Initializing\n"));
 
   netsnmp_register_scalar(
       netsnmp_create_handler_registration("afdxSwitchEDACTestResult", handle_afdxSwitchEDACTestResult,
                              afdxSwitchEDACTestResult_oid, OID_LENGTH(afdxSwitchEDACTestResult_oid),
                              HANDLER_CAN_RWRITE
       ));
}
 
int
handle_afdxSwitchEDACTestResult(netsnmp_mib_handler *handler,
                         netsnmp_handler_registration *reginfo,
                         netsnmp_agent_request_info   *reqinfo,
                         netsnmp_request_info         *requests)
{
   int ret;
   /* We are never called for a GETNEXT if it's registered as a
      "instance", as it's "magically" handled for us.  */

 
   /* a instance handler also only hands us one request at a time, so
      we don't need to loop over a list of requests; we'll only get one. */

 
   switch(reqinfo->mode) {
 
       case MODE_GET: case MODE_GETNEXT:
           snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER, &mydata
                                    /* XXX: a pointer to the scalar's data */,
 
     sizeof(mydata)
                                    /* XXX: the length of the data in bytes */);
           break;
 
       /*
        * SET REQUEST
        *
        * multiple states in the transaction.  See:
        * http://www.net-snmp.org/tutorial-5/toolkit/mib_module/set-actions.jpg
        */

 
 
       case MODE_SET_RESERVE1:
       //        /* or you could use netsnmp_check_vb_type_and_size instead */
       //    ret = netsnmp_check_vb_type(requests->requestvb, ASN_INTEGER);
       //    if ( ret != SNMP_ERR_NOERROR ) {
       //        netsnmp_set_request_error(reqinfo, requests, ret );
       //    }
          break;
 
       case MODE_SET_RESERVE2:
       //    /* XXX malloc "undo" storage buffer */
       //    if (/* XXX if malloc, or whatever, failed: */) {
       //        netsnmp_set_request_error(reqinfo, requests, SNMP_ERR_RESOURCEUNAVAILABLE);
       //    }
           break;
 
       case MODE_SET_FREE:
       //    /* XXX: free resources allocated in RESERVE1 and/or
       //       RESERVE2.  Something failed somewhere, and the states
       //       below won't be called. */
           break;
 
       case MODE_SET_ACTION:
           ///* XXX: perform the value change here */
   mydata = *(requests->requestvb->val.integer);
           //if (/* XXX: error? */) {
           //    netsnmp_set_request_error(reqinfo, requests, /* some error */);
           //}
           break;
 
       case MODE_SET_COMMIT:
       //    /* XXX: delete temporary storage */
       //    if (/* XXX: error? */) {
       //        /* try _really_really_ hard to never get to this point */
       //        netsnmp_set_request_error(reqinfo, requests, SNMP_ERR_COMMITFAILED);
       //    }
           break;
 
      case MODE_SET_UNDO:
       //    /* XXX: UNDO and return to previous value for the object */
       //    if (/* XXX: error? */) {
       //        /* try _really_really_ hard to never get to this point */
       //        netsnmp_set_request_error(reqinfo, requests, SNMP_ERR_UNDOFAILED);
       //    }
           break;
 
       default:
           /* we should never get here, so this is a really bad error */
           snmp_log(LOG_ERR, "unknown mode (%d) in handle_afdxSwitchEDACTestResult\n", reqinfo->mode );
           return SNMP_ERR_GENERR;
   }
 
   return SNMP_ERR_NOERROR;
}
 
 

Код:
https://sourceforge-net.translate.goog/p/net-snmp/mailman/message/14633956/?_x_tr_sl=en&_x_tr_tl=ru&_x_tr_hl=ru&_x_tr_pto=sc
17  Qt / Вопросы новичков / Re: Qt Таблица дел с созданием оповещений в определенное время : Апрель 30, 2022, 17:33


Ну например

Код
C++ (Qt)
struct Deal {
 
QString name;
QDate date;
QTime time;
 
}
 
 
Наследуйтесь от QAbstractTableModel
Переопределяйте функцию как Вам нужно выводить
данные в таблице.

Код
C++ (Qt)
virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0
 

Запускаем таймер в основном потоке и сравниваем
время, которое хранится в структуре с текущим временем
системы


18  Qt / Работа с сетью / Re: Net-SNMP, mib2c : Апрель 29, 2022, 11:54
Не выполняется snmpget  Непонимающий Непонимающий Непонимающий
Код:
snmpset -v2c -c public localhost .1.3.6.1.4.1.8419.11.1.1.0 = 5

Error in packet.
Reason: (genError) A general failure occured

Хотя snmpget, snmpwalk отрабатывают норм
Код:
 
snmpget -v2c -c public localhost .1.3.6.1.4.1.8419.11.1.1.0
AIRBUS-AFDX-SW-MIB::afdxSwitchEDACTestResult.0 = INTEGER: 10

Код:
snmpwalk -v2c -c public localhost .1.3.6.1.4.1.8419.11.1.1.0 
AIRBUS-AFDX-SW-MIB::afdxSwitchEDACTestResult.0 = INTEGER: 10

В MIB-файле ACCESS  read-write
MIB - файл
Код:
AIRBUS-AFDX-SW-MIB DEFINITIONS ::= BEGIN

IMPORTS enterprises, Counter, IpAddress, TimeTicks FROM RFC1155-SMI
             TRAP-TYPE  FROM RFC-1215
             OBJECT-TYPE FROM RFC-1212;

collins-Avionics   OBJECT IDENTIFIER ::= { enterprises 8419 }
AFDX               OBJECT IDENTIFIER ::= { collins-Avionics 11 }

-- Groups in AIRBUS AFDX Switch MIB
afdxSwitchPrivate    OBJECT IDENTIFIER ::= { AFDX 1 }

--
-- The afdxSwitchPrivate group
--
-- The afdxSwitchPrivate group contains objects related to the RC Switch
-- internal architecture.
--

afdxSwitchEDACTestResult OBJECT-TYPE
    SYNTAX INTEGER {
          passed (1),
          failed (2)
    }
    ACCESS  read-write
    STATUS  current
    DESCRIPTION
    "The result of the EDAC test executed on ground. The possible values are:
     - passed (1),
     - failed (2)."
    ::= { afdxSwitchPrivate 1 }

END


В конфиге rwcommunity public localhost
файл /usr/local/share/snmpd.conf
Код:
###############################################################################
#
# EXAMPLE.conf:
#   An example configuration file for configuring the Net-SNMP agent ('snmpd')
#   See the 'snmpd.conf(5)' man page for details
#
#  Some entries are deliberately commented out, and will need to be explicitly activated
#
###############################################################################
#
#  AGENT BEHAVIOUR
#

#  Listen for connections from the local system only
agentAddress  udp:127.0.0.1:161
#  Listen for connections on all interfaces (both IPv4 *and* IPv6)
#agentAddress udp:161,udp6:[::1]:161



###############################################################################
#
#  SNMPv3 AUTHENTICATION
#
#  Note that these particular settings don't actually belong here.
#  They should be copied to the file /var/lib/snmp/snmpd.conf
#     and the passwords changed, before being uncommented in that file *only*.
#  Then restart the agent

#  createUser authOnlyUser  MD5 "remember to change this password"
#  createUser authPrivUser  SHA "remember to change this one too"  DES
#  createUser internalUser  MD5 "this is only ever used internally, but still change the password"

#  If you also change the usernames (which might be sensible),
#  then remember to update the other occurances in this example config file to match.



###############################################################################
#
#  ACCESS CONTROL
#

                                                 #  system + hrSystem groups only
view   systemonly  included   .1.3.6.1.2.1.1
view   systemonly  included   .1.3.6.1.2.1.25.1
view   all         included   .1
                                                 #  Full access from the local host
#rocommunity public  localhost
rwcommunity public  localhost
                                                 #  Default access to basic system info
 rocommunity public  default    -V systemonly
                                                 #  rocommunity6 is for IPv6
 rocommunity6 public  default   -V systemonly

                                                 #  Full access from an example network
                                                 #     Adjust this network address to match your local
                                                 #     settings, change the community string,
                                                 #     and check the 'agentAddress' setting above
#rocommunity secret  10.0.0.0/16

                                                 #  Full read-only access for SNMPv3
 rouser   authOnlyUser
                                                 #  Full write access for encrypted requests
                                                 #     Remember to activate the 'createUser' lines above
# rwuser   authPrivUser   priv

#  It's no longer typically necessary to use the full 'com2sec/group/access' configuration
#  r[ow]user and r[ow]community, together with suitable views, should cover most requirements



###############################################################################
#
#  SYSTEM INFORMATION
#

#  Note that setting these values here, results in the corresponding MIB objects being 'read-only'
#  See snmpd.conf(5) for more details
sysLocation    Sitting on the Dock of the Bay
sysContact     Me <me@example.org>
                                                 # Application + End-to-End layers
sysServices    72


#
#  Process Monitoring
#
                               # At least one  'mountd' process
proc  mountd
                               # No more than 4 'ntalkd' processes - 0 is OK
proc  ntalkd    4
                               # At least one 'sendmail' process, but no more than 10
proc  sendmail 10 1

#  Walk the UCD-SNMP-MIB::prTable to see the resulting output
#  Note that this table will be empty if there are no "proc" entries in the snmpd.conf file


#
#  Disk Monitoring
#
                               # 10MBs required on root disk, 5% free on /var, 10% free on all other disks
disk       /     10000
disk       /var  5%
includeAllDisks  10%

#  Walk the UCD-SNMP-MIB::dskTable to see the resulting output
#  Note that this table will be empty if there are no "disk" entries in the snmpd.conf file


#
#  System Load
#
                               # Unacceptable 1-, 5-, and 15-minute load averages
load   12 10 5

#  Walk the UCD-SNMP-MIB::laTable to see the resulting output
#  Note that this table *will* be populated, even without a "load" entry in the snmpd.conf file



###############################################################################
#
#  ACTIVE MONITORING
#

                                    #   send SNMPv1  traps
 trapsink     localhost public
                                    #   send SNMPv2c traps
#trap2sink    localhost public
                                    #   send SNMPv2c INFORMs
#informsink   localhost public

#  Note that you typically only want *one* of these three lines
#  Uncommenting two (or all three) will result in multiple copies of each notification.


#
#  Event MIB - automatically generate alerts
#
                                   # Remember to activate the 'createUser' lines above
iquerySecName   internalUser      
rouser          internalUser
                                   # generate traps on UCD error conditions
defaultMonitors          yes
                                   # generate traps on linkUp/Down
linkUpDownNotifications  yes



###############################################################################
#
#  EXTENDING THE AGENT
#

#
#  Arbitrary extension commands
#
 extend    test1   /bin/echo  Hello, world!
 extend-sh test2   echo Hello, world! ; echo Hi there ; exit 35
#extend-sh test3   /bin/sh /tmp/shtest

#  Note that this last entry requires the script '/tmp/shtest' to be created first,
#    containing the same three shell commands, before the line is uncommented

#  Walk the NET-SNMP-EXTEND-MIB tables (nsExtendConfigTable, nsExtendOutput1Table
#     and nsExtendOutput2Table) to see the resulting output

#  Note that the "extend" directive supercedes the previous "exec" and "sh" directives
#  However, walking the UCD-SNMP-MIB::extTable should still returns the same output,
#     as well as the fuller results in the above tables.


#
#  "Pass-through" MIB extension command
#
#pass .1.3.6.1.4.1.8072.2.255  /bin/sh       PREFIX/local/passtest
#pass .1.3.6.1.4.1.8072.2.255  /usr/bin/perl PREFIX/local/passtest.pl

# Note that this requires one of the two 'passtest' scripts to be installed first,
#    before the appropriate line is uncommented.
# These scripts can be found in the 'local' directory of the source distribution,
#     and are not installed automatically.

#  Walk the NET-SNMP-PASS-MIB::netSnmpPassExamples subtree to see the resulting output


#
#  AgentX Sub-agents
#
                                           #  Run as an AgentX master agent
 master          agentx
                                           #  Listen for network connections (from localhost)
                                           #    rather than the default named socket /var/agentx/master
#agentXSocket    tcp:localhost:705











setserialno 462583681
##############################################################
#
# snmpNotifyFilterTable persistent data
#
##############################################################


engineBoots 28
oldEngineID 0x80001f888025d749712555646200000000
##############################################################
#
# ifXTable persistent data
#
ifXTable .1 14:0 18:0x $
ifXTable .2 14:0 18:0x $
ifXTable .3 14:0 18:0x $
##############################################################

Код обработчика агента
Код
C++ (Qt)
/*
* Note: this file originally auto-generated by mib2c
* using mib2c.scalar.conf
*/

 
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include "collins_Avionics.h"
 
 
static u_char mydata = 10;
 
/** Initializes the collins_Avionics module */
void
init_collins_Avionics(void)
{
   const oid afdxSwitchEDACTestResult_oid[] = { 1,3,6,1,4,1,8419,11,1,1 };
 
 DEBUGMSGTL(("collins_Avionics", "Initializing\n"));
 
   netsnmp_register_scalar(
       netsnmp_create_handler_registration("afdxSwitchEDACTestResult", handle_afdxSwitchEDACTestResult,
                              afdxSwitchEDACTestResult_oid, OID_LENGTH(afdxSwitchEDACTestResult_oid),
                              HANDLER_CAN_RWRITE
       ));
}
 
int
handle_afdxSwitchEDACTestResult(netsnmp_mib_handler *handler,
                         netsnmp_handler_registration *reginfo,
                         netsnmp_agent_request_info   *reqinfo,
                         netsnmp_request_info         *requests)
{
   int ret;
   /* We are never called for a GETNEXT if it's registered as a
      "instance", as it's "magically" handled for us.  */

 
   /* a instance handler also only hands us one request at a time, so
      we don't need to loop over a list of requests; we'll only get one. */

 
   switch(reqinfo->mode) {
 
       case MODE_GET: case MODE_GETNEXT:
           snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER, &mydata
                                    /* XXX: a pointer to the scalar's data */,
 
     sizeof(mydata)
                                    /* XXX: the length of the data in bytes */);
           break;
 
       /*
        * SET REQUEST
        *
        * multiple states in the transaction.  See:
        * http://www.net-snmp.org/tutorial-5/toolkit/mib_module/set-actions.jpg
        */

 
 
       //case MODE_SET_RESERVE1:
       //        /* or you could use netsnmp_check_vb_type_and_size instead */
       //    ret = netsnmp_check_vb_type(requests->requestvb, ASN_INTEGER);
       //    if ( ret != SNMP_ERR_NOERROR ) {
       //        netsnmp_set_request_error(reqinfo, requests, ret );
       //    }
       //   break;
 
       //case MODE_SET_RESERVE2:
       //    /* XXX malloc "undo" storage buffer */
       //    if (/* XXX if malloc, or whatever, failed: */) {
       //        netsnmp_set_request_error(reqinfo, requests, SNMP_ERR_RESOURCEUNAVAILABLE);
       //    }
       //    break;
 
       //case MODE_SET_FREE:
       //    /* XXX: free resources allocated in RESERVE1 and/or
       //       RESERVE2.  Something failed somewhere, and the states
       //       below won't be called. */
       //    break;
 
       case MODE_SET_ACTION:
           ///* XXX: perform the value change here */
   mydata = *(requests->requestvb->val.integer);
           //if (/* XXX: error? */) {
           //    netsnmp_set_request_error(reqinfo, requests, /* some error */);
           //}
           break;
 
       //case MODE_SET_COMMIT:
       //    /* XXX: delete temporary storage */
       //    if (/* XXX: error? */) {
       //        /* try _really_really_ hard to never get to this point */
       //        netsnmp_set_request_error(reqinfo, requests, SNMP_ERR_COMMITFAILED);
       //    }
       //    break;
 
       //case MODE_SET_UNDO:
       //    /* XXX: UNDO and return to previous value for the object */
       //    if (/* XXX: error? */) {
       //        /* try _really_really_ hard to never get to this point */
       //        netsnmp_set_request_error(reqinfo, requests, SNMP_ERR_UNDOFAILED);
       //    }
       //    break;
 
       default:
           /* we should never get here, so this is a really bad error */
           snmp_log(LOG_ERR, "unknown mode (%d) in handle_afdxSwitchEDACTestResult\n", reqinfo->mode );
           return SNMP_ERR_GENERR;
   }
 
   return SNMP_ERR_NOERROR;
}
 

Подскажите где может быть загвоздка Непонимающий Непонимающий Непонимающий
19  Qt / Работа с сетью / Re: Net-SNMP, mib2c : Апрель 24, 2022, 00:36
С mib2c вроде разобрались.
Файлы .h .cpp - есть. Перенес файлы в /agent/mibgroup/
Код:
./configure --with-mib-modules="name"
Код:
make
Код:
sudo make install

Запускаем агента
Код:
cd /usr/local/sbin/
./snmpd

Запустил snmpget
Код:
snmpget -v2c -c public localhost 1.3.6.1.4.1.8419.11.1.1
Timeout: No Response from localhost.

 Непонимающий

Смотрим лог-файл /var/log/snmp.log
Код:
Warning: no access control information configured.
  (Config search path: /usr/local/etc/snmp:/usr/local/share/snmp:/usr/local/lib/snmp:/home/evgen/.snmp)
  It's unlikely this agent can serve any useful purpose in this state.
  Run "snmpconf -g basic_setup" to help you configure the snmpd.conf file for this agent.
NET-SNMP version 5.9.1

Конфигурационный файл как я понял при запуске ./configure
нахлдится /var/net-snmp/snmpd.conf

Что в нем нужно прописать Непонимающий

20  Qt / Работа с сетью / Re: Net-SNMP, mib2c : Апрель 22, 2022, 11:43

MIB-file:
Код:

afdxSwitchLowBagValueLoopbackTestResult OBJECT-TYPE
    SYNTAX INTEGER {
          passed (1),
          failed (2)
    }
    ACCESS  read-only
    STATUS  current
    DESCRIPTION
    "The result of the Low Bag Value Loopback test executed on ground. The possible values are:
     - passed (1),
     - failed (2)."
    ::= { afdxSwitchPrivate 2 }


Код:
export MIBS="/home/robo/netsnmp/afdxswitch.mib"

Правильно ли выполняю работу с утилитой mib2c для переменной afdxSwitchTimestampCounterTestResult
Код:
mib2c -c mib2c.scalar.conf afdxSwitchLowBagValueLoopbackTestResult

Так как в результате получаю с-файл
Код
C++ (Qt)
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include "afdxSwitchLowBagValueLoopbackTestResult.h"
 
/** Initializes the afdxSwitchLowBagValueLoopbackTestResult module */
void
init_afdxSwitchLowBagValueLoopbackTestResult(void)
{
   const oid afdxSwitchLowBagValueLoopbackTestResult_oid[] = { 1,3,6,1,4,1,8419,11,1,2 };
 
 DEBUGMSGTL(("afdxSwitchLowBagValueLoopbackTestResult", "Initializing\n"));
 
   netsnmp_register_scalar(
       netsnmp_create_handler_registration("afdxSwitchLowBagValueLoopbackTestResult", handle_afdxSwitchLowBagValueLoopbackTestResult,
                              afdxSwitchLowBagValueLoopbackTestResult_oid, OID_LENGTH(afdxSwitchLowBagValueLoopbackTestResult_oid),
                              HANDLER_CAN_RONLY
       ));
}
 
int
handle_afdxSwitchLowBagValueLoopbackTestResult(netsnmp_mib_handler *handler,
                         netsnmp_handler_registration *reginfo,
                         netsnmp_agent_request_info   *reqinfo,
                         netsnmp_request_info         *requests)
{
   /* We are never called for a GETNEXT if it's registered as a
      "instance", as it's "magically" handled for us.  */

 
   /* a instance handler also only hands us one request at a time, so
      we don't need to loop over a list of requests; we'll only get one. */

 
   switch(reqinfo->mode) {
 
       case MODE_GET:
           snmp_set_var_typed_value(requests->requestvb, ASN_INTEGER,
 
                                    //_____________Что с этим делать?_________________
                                    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                                    /* XXX: a pointer to the scalar's data */,
                                    /* XXX: the length of the data in bytes */);
                                    //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
 
           break;
 
 
       default:
           /* we should never get here, so this is a really bad error */
           snmp_log(LOG_ERR, "unknown mode (%d) in handle_afdxSwitchLowBagValueLoopbackTestResult\n", reqinfo->mode );
           return SNMP_ERR_GENERR;
   }
 
   return SNMP_ERR_NOERROR;
}
 

И что я должен дописать вместо этого я не знаю
Код:
  /* XXX: a pointer to the scalar's data */,
  /* XXX: the length of the data in bytes */


21  Qt / Работа с сетью / Re: Net-SNMP, mib2c : Апрель 21, 2022, 14:04
Есть мибовский файл.
С помощью утилиты snmptranslate можно работать с oid.

Не могу понять как с помощью mib2c сгенерить код.

Код:
mib2c -c mib2c. mfd. conf что писать здесь? 

Наименование таблицы, имя переменной, наименование идентификатора из mib - файла?

Если указываю один из вышеперечисленных параметров, то выдается ошибка

Код:

This module can be used with tables, not branches or entire MIBs. Please specify and OID  that is a table. (OID: имя папретра)

22  Qt / Работа с сетью / Net-SNMP, mib2c : Апрель 21, 2022, 13:02
Доброго дня! Кто-нибудь работал с net- snmp и генерил файлы с кодом с помощью утилиты mib2c?
23  Qt / Общие вопросы / Re: Чтение и запись в файл в разных потоках : Сентябрь 09, 2021, 07:37
Но это кажется как-то не очень хорошей идей.
А почему?
Может есть какой-нибудь варинт асинхронного чтения и записи?
Не вижу откуда им взяться. Ну если неск "читателей", то ReadWriteLock - но здесь и это не проходит т.к. каждому нужна своя позиция в файле

Читаем из файла блоки информации определенного размера. Пишем естественно только в конец файла.

Поток на чтение
Код:

mutex_file.lock() ;

file. seek(pos) ;
file. read(but, size_block) ;

mutex_file.unlock() ;



Код:

mutex_file.lock() ;

file. seek(end_file) ;
file.write(buf, size_buf);

mutex_file.unlock() ;


 Стоит ли открывать и закрывать файл в потоках?  
24  Qt / Общие вопросы / Чтение и запись в файл в разных потоках : Сентябрь 08, 2021, 21:06
Всем доброго времени суток!
Встал вопрос чтения и записи в разных потоках.
Ответ кажется очевидным.
Берем файл мьючим его и читаем в одном потоке,
а в другом пишем.

Но это кажется как-то не очень хорошей идей.
Может есть какой-нибудь варинт асинхронного чтения и записи?
25  Qt / Пользовательский интерфейс (GUI) / Вывод большого количества строк : Сентябрь 07, 2021, 10:53
День добрый!!!

Есть буфер с большим количеством строк.  Нужно вывести их на  QTextBrowser.
Понятно что  в QTextBrowser  лучше больше 10000 строк лучше не пихать, а то  GUI лагать будет.

Хотелось бы сделать такую штуку, чтобы по прокрутки   slider  на scrollbar  текст менялся (внизу добавлялся новый, вверху убирался старый, когда крутим вниз и наоборот) , т. е  строки в зависимости от их порядка расположения добавляются и удаляются.

Подскажите есть ли какой-нибудь пример наработки или в каком направлении  копать?

Спасибо
26  Qt / Установка, сборка, отладка, тестирование / Re: QtCreator & Perf : Март 22, 2021, 19:04
интуитивно, методом проб и ошибок


"Ты кем, работаешь?"
"Инженером - чем меньше работаю, тем меньше вреда!"
27  Qt / Установка, сборка, отладка, тестирование / Re: QtCreator & Perf : Март 22, 2021, 14:28
мастерством использования perf я не владею, кроме как увидеть что "гдето чтото - тормозит"
И как тогда с помощью Perf узнать" где и что тормозит"?
28  Qt / Установка, сборка, отладка, тестирование / Re: QtCreator & Perf : Март 22, 2021, 12:54
QtCreator  из под рута , в нем запускал анализатор производительности...

1. хм, а есть смысл запускать именно из креатора ?
2. работает ли sudo perf top ?

По второму пункту: да, работает
По первому пункту
Мне кажется что да, хотелось проанализировать свой код. Это вроде и удобнее...
Я понимаю что есть другие варианты, но этот самый простой и удобный , опять же как мне показалось.

Если есть другая хорошая альтернатива, чтобы можно было оценить свой код и места большой
загруженности процессора в коде - то подскажите, буду признателен, я всегда готов выслушать
29  Qt / Установка, сборка, отладка, тестирование / Re: QtCreator & Perf : Март 21, 2021, 10:04
У вас, скорее прав не хватает.
Попробуйте
Код:
sudo sh -c 'echo 1 >/proc/sys/kernel/perf_event_paranoid'

 Я это уже пробовал это , в самом первом сообщении это:
Цитировать
Ну или набрал две команды как описанно в статье
Код:
sudo sh -c 'echo 1 >/proc/sys/kernel/perf_event_paranoid'
sudo sysctl -w kernel.perf_event_paranoid=1

Помогло, но...
Код:
WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,
check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid.

Samples in kernel functions may not be resolved if a suitable vmlinux
file is not found in the buildid cache or in the vmlinux path.

Samples in kernel modules won't be resolved at all.

If some relocation was applied (e.g. kexec) symbols may be misresolved
even with a suitable vmlinux or kallsyms file.

Couldn't record kernel reference relocation symbol
Symbol resolution may be skewed if relocation was used (e.g. kexec).
Check /proc/kallsyms permission or run as root.
QHostAddress("127.0.0.1")
[ perf record: Woken up 27 times to write data ]
[ perf record: Captured and wrote 0,000 MB - ]

30  Qt / Установка, сборка, отладка, тестирование / Re: QtCreator & Perf : Март 20, 2021, 00:35
Вы бы лучше сюда ошибку скопировали. "Жалобы на то что версия ядра линуха не соответствует версии perf" - это не совсем понятно.
P.S. Хотя, есть подозрение, что вы взяли версию perf одну, а само ядро другое. Если вы говорите за https://perf.wiki.kernel.org/index.php/Main_Page, то в ашем случае либо ставить ядро под perf, либо брать perf под ядро.
P.P.S. Допустим ядро 5.4.0-67 != 5.4.94

Вывод в приложения
Код:
perf_event_open(..., PERF_FLAG_FD_CLOEXEC) failed with unexpected error 13 (Отказано в доступе)
perf_event_open(..., 0) failed unexpectedly with error 13 (Отказано в доступе)
Error:
You may not have permission to collect stats.

Consider tweaking /proc/sys/kernel/perf_event_paranoid,
which controls use of the performance events system by
unprivileged users (without CAP_SYS_ADMIN).

The current value is 3:

  -1: Allow use of (almost) all events by all users
      Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK
>= 0: Disallow ftrace function tracepoint by users without CAP_SYS_ADMIN
      Disallow raw tracepoint access by users without CAP_SYS_ADMIN
>= 1: Disallow CPU event access by users without CAP_SYS_ADMIN
>= 2: Disallow kernel profiling by users without CAP_SYS_ADMIN

To make this setting permanent, edit /etc/sysctl.conf too, e.g.:

kernel.perf_event_paranoid = -1

Страниц: 1 [2] 3 4 ... 65

Страница сгенерирована за 0.21 секунд. Запросов: 23.